简体   繁体   English

由于找不到模型属性而通过了Spring MVC Controller测试

[英]Spring MVC Controller Test passing due to not finding model attribute

I have created the Home Controller below. 我在下面创建了家庭控制器。 This controller fetches the 5 dummy posts I have created in the "PostRepository" class through PostService class. 该控制器通过PostService类获取在“ PostRepository”类中创建的5个虚拟帖子。

@Controller
public class HomeController {

    @Autowired
    PostService postService;

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

        return "home";
    }
}

I have implemented the following test.. 我已经执行了以下测试。

@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"));
    }

}

The test has successfully passed. 测试已成功通过。 But the attribute should exist. 但是属性应该存在。

You are mixing two incompatible features of Spring's testing support. 您正在混合使用Spring测试支持的两个不兼容的功能。

If you instantiate the controller within the test, you need to use MockMvcBuilders.standaloneSetup() . 如果在测试中实例化控制器,则需要使用MockMvcBuilders.standaloneSetup()

If you are using the Spring TestContext Framework (ie, @ContextConfiguration , etc.), then you need to use MockMvcBuilders.webAppContextSetup() . 如果您使用的是Spring TestContext Framework@ContextConfiguration等),则需要使用MockMvcBuilders.webAppContextSetup()

Thus, the following is the appropriate configuration for your test. 因此,以下是适合您的测试的配置。

@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));
    }
}

Regards, 问候,

Sam ( author of the Spring TestContext Framework ) Sam( Spring TestContext Framework的作者

如果那是完整的代码,那么您就丢失了

@RunWith(SpringJUnit4ClassRunner.class)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM