Spring 由于未找到模型属性,MVC 控制器测试通过

Spring MVC Controller Test passing due to not finding model attribute

我在下面创建了家庭控制器。该控制器通过 PostService class.

获取我在 "PostRepository" class 中创建的 5 个虚拟帖子
@Controller
public class HomeController {

    @Autowired
    PostService postService;

    @RequestMapping("/")
    public String getHome(Model model){
        model.addAttribute("Post", postService);

        return "home";
    }
}

我已经实施了以下测试..

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfig.class})
@WebAppConfiguration
public class ControllerTest {

    @Test //Test the Home Controller
    public void TestHomePage() throws Exception{
        HomeController homeController = new HomeController();
        MockMvc mockMvc = standaloneSetup(homeController).build();

        mockMvc.perform(get("/"))
                .andExpect(view().name("home"))
                .andExpect(model().attributeDoesNotExist("Post"));
    }

}

测试成功通过。但是该属性应该存在。

如果这是完整的代码,那你就漏了

@RunWith(SpringJUnit4ClassRunner.class)

您正在混合使用 Spring 测试支持的两个不兼容功能。

如果在测试中实例化控制器,则需要使用MockMvcBuilders.standaloneSetup()

如果您使用 Spring TestContext Framework(即 @ContextConfiguration 等),则需要使用 MockMvcBuilders.webAppContextSetup() .

因此,以下是适合您测试的配置。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebConfig.class)
@WebAppConfiguration
public class ControllerTest {

    @Autowired
    WebApplicationContext wac;

    @Autowired
    PostService postService;

    @Test
    public void TestHomePage2() throws Exception {
        MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

        mockMvc.perform(get("/"))
                .andExpect(view().name("home"))
                .andExpect(model().attribute("Post",postService));
    }
}

此致,

Sam(Spring TestContext Framework 的作者)