2017-07-25 13 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 –

相關問題