我正在尝试使用 spring boot 学习 junit 测试。通常我不会只问空指针异常,但现在我找不到丢失的东西。@RunWith(SpringRunner.class)@SpringBootTest(webEnvironment = WebEnvironment.MOCK)@ActiveProfiles("dev")@AutoConfigureMockMvc@WithMockUser(username = "user", password = "secret", authorities = "USER")public class OwnersWebMVCTests { @Autowired private MockMvc mockMvc; @Test public void testOwners() throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/owners"); ResultActions resultActions = mockMvc.perform(requestBuilder); MvcResult mvcResult = resultActions.andReturn(); ModelAndView mav = mvcResult.getModelAndView(); MatcherAssert.assertThat(mav.getViewName(), Matchers.equalTo("owners")); MatcherAssert.assertThat(mav.getModel().containsKey("owners"), Matchers.is(true)); }}ModelAndView mav = mvcResult.getModelAndView(); 返回 null。
1 回答
慕少森
TA贡献2019条经验 获得超9个赞
问题与控制器有关,与测试无关。
可能的问题:您的控制器未被扫描!我这样说是因为您希望拥有相同的 GET url 并查看“所有者”=> 这将失败,因为它将重定向到自身。
解决方法:请确保控制器和spring boot test的包名相同或者导入一个配置进行扫描。
OwnerController -> src/main/java/ org.test
TestOwnerController -> src/test/java/ org.test
相同的包名:org.test
如果你需要有不同的包名,你可以添加到你的测试中
@ComponentScan("org.owner")
-> 其中 org.owner 是 OwnerController 的包
改进:您可以将测试方法重写为
mockMvc.perform(get("/owners"))
.andExpect(model().attributeExists("owners"))
.andExpect(view().name("view"));
还请更改返回视图的名称以确保不会失败:
@GetMapping(value = "/owners")
public ModelAndView getOwnersView() {
return new ModelAndView("view", Collections.singletonMap("owners", new Object()));
}
添加回答
举报
0/150
提交
取消