我想测试我的 Controller ,但我很难模拟对象。我有这样的非常简单的方法。
@RequestMapping(value = "/places", method = RequestMethod.GET)
public String showPlacesByQuery(Model model, @RequestParam(value = "q", required = false) String query) {
Location location = geolocationParser.getCoords(query); //this line cause NPE
List placesList = placeService.findPublicPlaces(location, 0);
model.addAttribute("query", query);
model.addAttribute("placesList", placesList);
return "places/list";
}
我写了测试,得到 NullPointerException
。我认为原因是geolocationParser.getCoordS(query)
返回null
?或者整个作业有问题 Location location = geolocationParser.getCoords(query);
@Mock
GeolocationParser geolocationParser;
@Mock
PlaceService placeService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testShowPlacesByQuery() throws Exception {
String query = "SomeQuery";
PlaceController placeController = new PlaceController();
Location location = mock(Location.class);
location.setCity("someString");
location.setLatitude("54.2323");
location.setLongitude("18.2323");
when(geolocationParser.getCoords(Mockito.anyString())).thenReturn(location);
List<Place> expectedPlaces = asList(new Place(), new Place());
when(placeService.findPublicPlaces(location, 0)).thenReturn(expectedPlaces);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(placeController).build();
mockMvc.perform(get("/places").param("q", query))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("places/list"));
}
我花了几个小时以不同的方式让它发挥作用,但没有结果。
最佳答案
如果您正在测试 PlaceController
类,则不应手动为该类创建实例。使用@InjectMocks。
@Mock
private FormServiceImpl formService;
@Mock
private FormDao formDao;
@InjectMocks
private PlaceController placeController;
并从此处将其删除
@Test
public void testShowPlacesByQuery() throws Exception {
String query = "SomeQuery";
//PlaceController placeController = new PlaceController();
关于java - 单元测试期间 POJO 对象上的 NullPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33904057/