26
votes

I am trying to test some legacy code using Mockito, and the method is a of type void.

I have stubbed out a lot of the calls to methods in other classes, this works fine. However, I also need to be able to stub out certain calls to other methods inside the same class.

Currently this is not working.

e.g. My Class is like below:

public class Test {


    public Test(dummy dummy) {

    }

    public void checkTask(Task task, List <String> dependencyOnLastSuccessList) throws TaskException {
        callToOtherClass.method1 // This works fine, I can stub it using mockito

        updateAndReschedule(Long id, String message) // call to method in same class, I cannot stub it
    }

    public void updateAndReschedule(Long id, String message) {
        //method logic.....
    }
}

This is my testClass showing what I have at the minute:

@Test
public void testMyMethod() {
    Test testRef = new Test(taskJob);
    Test spy = spy (testRef);

    // when a particular method is called, return a specific  object
    when(callToOtherClass.method1).thenReturn(ObjectABC);

    //doNothing when my local method is called
    doNothing().when(spy).updateAndReschedule(1, "test");       
    //make method call
    spy.checkTask(ts, taskDependencies);

}
2

2 Answers

30
votes

You should instantiante testRef as follows:

Test testRef = new Test(taskJob) {

    public void updateAndReschedule(Long id, String message) {
        //do nothing
    }

};

No need for the spy.

3
votes

In my opinion the spy object instead of mock. Spy is a mock created as a proxy to an existing real object; some methods can be stubbed, while the unstubbed ones are forwarded to the covered object

The spy is more elegant than anonymous implementation of chosen methods

Look at the example:

Mockito: Trying to spy on method is calling the original method

the nice article about mockito You can read

http://refcardz.dzone.com/refcardz/mockito