NullPointer exception every time I try to run my Junit test case
Every time I try to run a junit test case I get a null pointer exception and also when I tried to throw the exception every time the function returns NULL. Here is the code.
RestaurantRepository.java
package org.springsource.restbucks;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
public interface RestaurantRepository extends PagingAndSortingRepository<Restaurant, Long> {
@Query("SELECT p FROM Restaurant p Where (p.id)=(:Id) and p.deleted=false")
Restaurant findById(@Param("Id") long Id);
@Query("SELECT p FROM Restaurant p Where LOWER(p.name)=LOWER(:name) and p.deleted = false")
Restaurant findByName(@Param("name") String name);
}
RestaurantController.java
@RestController
public class RestaurantController {
@Autowired
RestaurantRepository repository;
@RequestMapping(value = "/restaurants/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseEntity<Restaurant> getRestaurant(@PathVariable("id") long restaurantId) {
Restaurant responseRestaurant = repository.findOne(restaurantId);
if(responseRestaurant==null){
logger.error("No Restaurant found with id:"+restaurantId);
return new ResponseEntity<Restaurant>(HttpStatus.NOT_FOUND);
}else if(responseRestaurant.isDeleted()==true){
logger.error("Restaurant Object is deleted");
return new ResponseEntity<Restaurant>(HttpStatus.NOT_FOUND);
}else{
return new ResponseEntity<Restaurant>(responseRestaurant,HttpStatus.OK);
}
}
}
RestaurantRepositoryTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class RestaurantRepositoryTest{
@Autowired
private RestaurantRepository repository;
@Test
public void testfindById() throws Exception{ //testing findbyid method in restaurant repository
Restaurant responseRestaurant = repository.findByName("xyz"); //getting error over here
assertEquals("xyz",responseRestaurant.getName());
}
}
I am getting a null pointer exception whenever I run mvn test . the stack trace is below what I get in the terminal.
-
testfindById (org.springsource.restbucks.RestaurantRepositoryTest) Elapsed time: 0.018 s <ERROR! java.lang.NullPointerException: null in
-
org.springsource.restbucks.RestaurantRepositoryTest.testfindById (RestaurantRepositoryTest.java:19)
what should i do to successfully complete my test?
source to share
You are using this as a pure unit test with no Spring context. Therefore, the repository will not be auto-updated. You should be able to fix this by adding some annotations at the beginning of the test class.
If you are using Spring Boot then the following should work: Spring Boot to do all the hard work:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
You can also load a Spring class @Configuration
that initializes your repos (in my case it's called DbConfig
), for example:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { DbConfig.class },
loader = AnnotationConfigContextLoader.class)
source to share
Your test does not start the Spring context at all, so annotations are completely ignored. The best solution is to change the controller class to use the repository as a constructor argument instead of using field injection. This allows you to pass in a simple mock like the Mockito mock and avoid the complexity of running a Spring context to run a unit test.
source to share