13

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.

1 Answer 1

23

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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()); } }
Thanks a lot @Branislav. Please also let me know if RequestMapping("/rest/getInventoryBySoldToCustomer/{customerId}/{countryCode}") then test method can be like this : Test public void testgetInventoryDeatilsResponse() throws Exception { this.mockMvc.perform(get("/rest/getInventoryBySoldToCustomer/{customerId}/{countryCode}", 3,8)) .andExpect(status().isOk()); }
@nish Judging by documentation, yes you can. Since get method is taking variable number of arguments.
my class is like this: RestController public class InventoryController { Autowired private JdbcTemplate jdbcTemplate; RequestMapping("/rest/getInventoryBySoldToCustomer/{customerId}/{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;}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.