Junit Test cases for Spring MVC 4 controller to check @PathVariable parameters in @RequestMapping

20,113

Create a mock of your controller and use MockMvc to test your methods:

import static org.springframework.test.web.ModelAndViewAssert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({/* include live config here
    e.g. "file:web/WEB-INF/application-context.xml",
    "file:web/WEB-INF/dispatcher-servlet.xml" */})
public class EquipmentControllerTest {

    private MockMvc mockMvc;

    private EquipmentController controller;

    @Before
    public void setUp() {

       this.mockMvc = MockMvcBuilders.standaloneSetup(equipmentController).build()
    }

    @Test
    public void testgetEquipment() throws Exception {
      this.mockMvc.perform(get("/rest/equipment/{Number}", 3))
           .andExpect(status().isOk())
    }
}

where "3" represents value of your path variable.

Share:
20,113
Nishant Kumar
Author by

Nishant Kumar

Updated on July 09, 2022

Comments

  • Nishant Kumar
    Nishant Kumar almost 2 years

    I have following controller code for which I have to write JUnit test case.

    public class EquipmentController {
    
        private Map<String, Equipment> equiList = new HashMap <String,Equipment>();
    
        @RequestMapping("/rest/equipment/{Number}")
        public Equipment getEquipment(@PathVariable String Number){
    
            if(!equiList.containsKey(Number)){
                lNumber = DEFAULT;
            }
            return equiList.get(Number);
    
        }
    }
    

    I'm writing the JUnit test case for the same as below:

    import static org.springframework.test.web.ModelAndViewAssert.*;
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({/* include live config here
        e.g. "file:web/WEB-INF/application-context.xml",
        "file:web/WEB-INF/dispatcher-servlet.xml" */})
    public class EquipmentControllerTest {
    
        @Inject
        private ApplicationContext applicationContext;
    
        private MockHttpServletRequest request;
        private MockHttpServletResponse response;
        private HandlerAdapter handlerAdapter;
        private EquipmentController controller;
    
        @Before
        public void setUp() {
           request = new MockHttpServletRequest();
           response = new MockHttpServletResponse();
           handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
           // Get the controller from the context here
           controller = new EquipmentController();
        }
    
        @Test
        public void testgetEquipment() throws Exception {
           request.getUriString()("lNumber");
           final Equipment equip = handlerAdapter.handle(request, response, 
               controller);
           assertViewName(equip, "view");
        }
    }
    

    But am not sure if this test class is correct or not as I am new to JUnit.

    Can anyone please suggest how to do this.

  • Nishant Kumar
    Nishant Kumar over 8 years
    Thanks @Branislav for your reply.Did you mean something like this :RunWith(SpringJUnit4ClassRunner.class) public class EquipmentControllerTest { Before public void setUp() { EquipmentController equipmentController; MockMvc mockMvc; this.mockMvc = MockMvcBuilders.standaloneSetup(equipmentController).build()‌​; } Test public void testgetEquipment(){ this.mockMvc.perform(get("/rest/equipment/{lNumber}", 3)) .andExpect(status().isOk()); } }
  • Nishant Kumar
    Nishant Kumar over 8 years
    Thanks a lot @Branislav. Please also let me know if RequestMapping("/rest/getInventoryBySoldToCustomer/{customer‌​Id}/{countryCode}") then test method can be like this : Test public void testgetInventoryDeatilsResponse() throws Exception { this.mockMvc.perform(get("/rest/getInventoryBySoldToCustome‌​r/{customerId}/{coun‌​tryCode}", 3,8)) .andExpect(status().isOk()); }
  • Branislav Lazic
    Branislav Lazic over 8 years
    @nish Judging by documentation, yes you can. Since get method is taking variable number of arguments.
  • Nishant Kumar
    Nishant Kumar over 8 years
    my class is like this: RestController public class InventoryController { Autowired private JdbcTemplate jdbcTemplate; RequestMapping("/rest/getInventoryBySoldToCustomer/{custom‌​erId}/{countryCode}"‌​) public Inventory getInventoryDeatilsResponse( PathVariable String customerId, PathVariable String countryCode) { Inventory inventory = initInventory(); return inventory; } private Inventory initInventory() { Inventory inventory = new Inventory(); //do something return inventory;}}