Akshay Shah
Akshay Shah

Reputation: 490

NullPointer Exception everytime I try to run my Junit Test Case

Every time i try to run the junit test case , i get null pointer exception and also when i tried to hadle the exception everytime the function returns NULL value. 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 null pointer exception whenever i run mvn test . the stack trace is below what i get displayed in terminal.

what shall i do to run my test successfully??

Upvotes: 4

Views: 12900

Answers (2)

Your test is not starting up a Spring context at all, so the annotations are completely ignored. The best solution is to modify your controller class to take the repository as a constructor argument instead of using field injection. This allows you to pass in a simple mock, such as a Mockito mock, and avoid the complexity of starting up a Spring context to run a unit test.

Upvotes: 0

Steve
Steve

Reputation: 9480

You're running that as a pure unit test with no Spring context. Therefore, the repository will not be autowired. You should be able to fix that by adding a few annotations to the top of your test class.

If using Spring Boot, then something like the following should work, to let Spring Boot do all the hard work:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)

You can alternatively load the Spring @Configuration class which would initialise your repositories (In my case, this is called DbConfig), like so:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { DbConfig.class }, 
                      loader = AnnotationConfigContextLoader.class)

Upvotes: 2

Related Questions