2017-07-25 51 views
0

我在下面创建了主控制器。此控制器通过PostService类获取我在“PostRepository”类中创建的5个虚拟帖子。Spring MVC Controller由于未找到模型属性而导致测试通过

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

} 

测试已顺利通过。但属性应该存在。

+1

(春季TestContext框架作者)你应该把一个更完整的代码(至少你完整的HomeController,整个错误消息,看看哪些行是错误的,...) – RemyG

+0

@RemyG,谢谢!我已根据您的建议更新了该文章。 –

回答

1

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

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

如果您使用的是了Spring TestContext框架(即@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)); 
    } 
} 

问候,

山姆

+0

谢谢@Sam Brannen,这非常有意义!我正在混合推荐的两种方法。加载我的Spring MVC配置并创建一个没有加载Spring配置的控制器实例。我编辑了我的代码并删除了standaloneSetup,因为这不适用。 –

0

如果是完整的代码,那么你缺少

@RunWith(SpringJUnit4ClassRunner.class)

+0

这不能解决问题,仍然会收到相同的错误消息。我已更新我的问题以包含您的建议。谢谢@Irwan Hendra –

相关问题