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

心不动则不痛 提交于 2019-12-22 10:58:58

问题


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 ModelAndView to make it possible, but I'd like to use String because it is simpler. It's not must though.

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


回答1:


You can use Spring MVC Test:

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

And here is fully illustrated example




回答2:


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.




回答3:


You can use Mockito for that.

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

}


来源:https://stackoverflow.com/questions/40120991/spring-mvc-how-to-unit-test-models-attribute-from-a-controller-method-that-ret

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!