Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 327
user2652379 Avatar asked Oct 19 '16 02:10

user2652379


People also ask

How do you write a unit test case for a controller?

Writing a Unit Test for REST Controller First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object.

What is the use of model Addattribute () in spring?

Furthermore, there's also an addAttributes() method. Its purpose is to add values in the Model that'll be identified globally. That is, every request to every controller method will return a default value as a response.

What is WebMvcTest?

@WebMvcTest annotation is used for Spring MVC tests. It disables full auto-configuration and instead apply only configuration relevant to MVC tests. The WebMvcTest annotation auto-configure MockMvc instance as well.


2 Answers

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

like image 161
Sergii Getman Avatar answered Oct 19 '22 05:10

Sergii Getman


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

}
like image 20
mh-dev Avatar answered Oct 19 '22 06:10

mh-dev