I am trying to write some junit test for my Spring MVC controller and so far I am able to do it successfully. I am using Spring Mock along with jmockit as well.
Below is my method in the DataController
controller -
@RequestMapping(value = "processWork", method = RequestMethod.GET)
public @ResponseBody
DataResponse processWork(@RequestParam("conf") final String value, @RequestParam("dc") final String dc) {
// .. some code here
SomeOtherClass modifier = new SomeOtherClass(zookClient);
List<Map<String, String>> mappings = getMappings(dc);
modifier.processTask(value, mappings);
// .. some code here
}
Now in SomeOtherClass
, processTask
method is like this -
public void processTask(String value, List<Map<String, String>> mappings) throws Exception {
// some code here
}
Below is my junit test which I wrote for the processWork
method in the DataController
class.
private MockMvc mockMvc;
@Test
public void test03_processWork() throws Exception {
mockMvc.perform(
get("/processWork").param("conf", "shsysysys").param("dc", "eux")).andDo(print()).andExpect(status().isOk());
}
Problem Statement:-
Now the problem with this is, whenever I am running test03_processWork
unit test, it goes into processWork
method of my controller (which is fine) and then it calls processTask
method of my SomeOtherClass
and that is what I want to avoid.
Meaning, is there any way, I can mock processTask
method of SomeOtherClass
to return some default value, instead of running actual code what is there in processTask
method?
Currently with my junit test run, it is also calling processTask
method of SomeOtherClass
and the code inside processTask
is also running and that's what I want to avoid. I don't want any of the code which is there in processTask
to run by mocking using jmockit?
Is this possible to do?
You can use JMockit to mock your public void
method like this:
new MockUp<SomeOtherClass>() {
@Mock
public void processTask(String value, List<Map<String, String>> mappings) throws Exception {
System.out.println("Hello World");
}
};
Just add it above the mock at the starting of your unit test.