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

每次我尝试运行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秒<< null at
> org.springsource.restbucks.RestaurantRepositoryTest.testfindById(RestaurantRepositoryTest.java:19)

我该怎么做才能成功运行我的测试?

最佳答案 您将其作为纯单元测试运行,没有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)
点赞