简体   繁体   English

Spring MVC:如何从返回String的控制器方法单元测试Model的属性?

[英]Spring MVC: How to unit test Model's attribute from a controller method that returns String?

For example, 例如,

package com.spring.app;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(final Model model) {
        model.addAttribute("msg", "SUCCESS");
        return "hello";
    }

}

I want to test model 's attribute and its value from home() using JUnit. 我想使用JUnit从home()测试model的属性及其值。 I can change return type to ModelAndView to make it possible, but I'd like to use String because it is simpler. 我可以将返回类型更改为ModelAndView以使其成为可能,但我想使用String因为它更简单。 It's not must though. 但这不是必须的。

Is there anyway to check model without changing home() 's return type? 无论如何检查model而不改变home()的返回类型? Or it can't be helped? 或者它无法帮助?

You can use Spring MVC Test : 你可以使用Spring MVC Test

mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(model().attribute("msg", equalTo("SUCCESS"))) //or your condition

And here is fully illustrated example 这里有充分说明的例子

I tried using side effect to answer the question. 我尝试使用副作用来回答这个问题。

@Test
public void testHome() throws Exception {
    final Model model = new ExtendedModelMap();
    assertThat(controller.home(model), is("hello"));
    assertThat((String) model.asMap().get("msg"), is("SUCCESS"));
}

But I'm still not very confident about this. 但我对此仍然不是很有信心。 If this answer has some flaws, please leave some comments to improve/depreciate this answer. 如果这个答案有一些缺陷,请留下一些评论来改进/贬低这个答案。

You can use Mockito for that. 你可以使用Mockito。

Example: 例:

@RunWith(MockitoJUnitRunner.class) 
public HomeControllerTest {

    private HomeController homeController;
    @Mock
    private Model model;

    @Before
    public void before(){
        homeController = new HomeController();
    }

    public void testSomething(){
        String returnValue = homeController.home(model);
        verify(model, times(1)).addAttribute("msg", "SUCCESS");
        assertEquals("hello", returnValue);
    }

}

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

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