0

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?

john
  • 11,311
  • 40
  • 131
  • 251
  • Downvoters, care to explain what is wrong? I am happy to improve my question if there are any mistakes from me. I am still learning on mocking stuff. – john Jun 09 '14 at 02:12
  • Please see MockUp<> examples at http://jmockit.googlecode.com/svn/trunk/www/tutorial/AnExample.html – Jayan Jun 09 '14 at 03:40

1 Answers1

1

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.

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
arsenal
  • 23,366
  • 85
  • 225
  • 331
  • Given a class with 3 methods of which 1 is void returning method, I mock the other 2 with Expectations. I see for void returning method alone I cannot use MockUp as both can't be used in 1 test case. What's the way to achieve this? – Ramya K Sharma Nov 29 '16 at 17:52