gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:30:10 26 4
gpt4 key购买 nike

我在下面创建了家庭 Controller 。该 Controller 通过 PostService 类获取我在“PostRepository”类中创建的 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"));
}

}

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

最佳答案

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

如果您在测试中实例化 Controller ,则需要使用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 框架的作者)

关于java - Spring MVC Controller 由于找不到模型属性而测试通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45306261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com