每次我尝试运行我的Junit测试用例时都会出现NullPointer异常

时间:2015-01-07 09:37:29

标签: spring junit nullpointerexception

每次我尝试运行junit测试用例时,我都会得到空指针异常,并且每当函数返回NULL值时我都尝试使用异常。这是代码。

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());           
    }   
}

每当我运行 mvn test 时,我都会收到空指针异常。堆栈跟踪低于我在终端中显示的内容。

  • testfindById(org.springsource.restbucks.RestaurantRepositoryTest) 经过的时间:0.018秒<&lt;&lt;错误!显示java.lang.NullPointerException:

  • 时为null
  • org.springsource.restbucks.RestaurantRepositoryTest.testfindById(RestaurantRepositoryTest.java:19)

如何成功运行我的测试?

2 个答案:

答案 0 :(得分:2)

您将其作为纯单元测试运行,没有Spring上下文。因此,存储库不会自动装配。您应该能够通过在测试类的顶部添加一些注释来解决这个问题。

如果使用Spring Boot,那么下面的内容应该可行,让Spring Boot做所有艰苦的工作:

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

您也可以加载Spring @Configuration类来初始化您的存储库(在我的例子中,这称为DbConfig),如下所示:

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

答案 1 :(得分:0)

您的测试根本没有启动Spring上下文,因此完全忽略了注释。最好的解决方案是修改控制器类以将存储库作为构造函数参数而不是使用字段注入。这允许您传入一个简单的模拟,例如Mockito模拟,并避免启动Spring上下文来运行单元测试的复杂性。