maxi_hammerl
maxi_hammerl

Reputation: 3

Mockito: Intercepting method call without reference to object

I want to test the following example code:

public class Example {
  ...
  public void doStuff() {
    ...
    Lift lift = new Lift();
    lift.call(5);
    ...
  }
  ...
}

How can I 'intercept' lift.call(5)? Generally I would use when(lift.call(anyInt()).thenReturn(...), but I have no reference to the Lift object.

Upvotes: 0

Views: 940

Answers (2)

John Stringer
John Stringer

Reputation: 587

You can't do it with mockito alone. The cleanest solution is to refactor your code so you can have access to it. However if that's not an option then "power mockito" is what you want. Grab "powermock-api-mockito"+"powermock-module-junit4" and then something like this will do the trick:

import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Example.class)
public class ExampleTest {
    private Example testSubject;

    @Mock
    private Lift lift;

    @Test
    public void testDoStuff() throws Exception {
        testSubject.doStuff();
        verify(lift).call(5);
    }

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        PowerMockito.whenNew(Lift.class).withNoArguments().thenReturn(lift);
        testSubject = new Example();
    }
}

Upvotes: 1

Januson
Januson

Reputation: 4841

Can you modify the Example class? If yes, the simplest way would be to extract the Lift dependency and provide it via constructor. Like this:

public class Example {

    private final Lift lift;

    public Example(Lift lift) {
        this.lift = lift;
    }

    public void doStuff() {
        this.lift.call(5);
    }
}

Then you can stub lift as you want since now you have access to the instance.

Upvotes: 0

Related Questions