java Spring MVC:如何从返回字符串的控制器方法对模型的属性进行单元测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40120991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:56:17  来源:igfitidea点击:

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

javaspringunit-testingspring-mvcjunit

提问by user2652379

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. I can change return type to ModelAndViewto make it possible, but I'd like to use Stringbecause it is simpler. It's not must though.

我想使用 JUnit测试model的属性及其值home()。我可以将返回类型更改ModelAndView为使其成为可能,但我想使用String它,因为它更简单。但这不是必须的。

Is there anyway to check modelwithout changing home()'s return type? Or it can't be helped?

无论如何要检查model而不更改home()的返回类型?还是无能为力?

回答by Sergii Getman

You can use Spring MVC Test:

您可以使用Spring MVC 测试

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

And hereis fully illustrated example

在这里充分说明例子

回答by user2652379

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.

但我对此仍然不是很有信心。如果这个答案有一些缺陷,请留下一些评论来改进/贬低这个答案。

回答by mh-dev

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

}