亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ModelAndView 返回 null SpringBootTest

ModelAndView 返回 null SpringBootTest

慕婉清6462132 2021-10-27 19:19:41
我正在嘗試使用 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 并查看“所有者”=> 這將失敗,因為它將重定向到自身。


解決方法:請確??刂破骱蛃pring 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()));

}


查看完整回答
反對 回復 2021-10-27
  • 1 回答
  • 0 關注
  • 509 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號