forste
forste

Reputation: 1133

how to setup a call to method of mocked object in mockito without calling the original method itself

mockito-version: 1.9.0

I want to setup a call to a method of a mocked object in mockito without calling the original method itself:

EDIT: this example actually works as expect, i.e. the body method "test()" of does not get executed. However, after further investigation I noticed that the original method had the default visibility modifier and I suspect this to cause problems since after changing it to public (shouldn't this be the same?!) it works as expected.

e.g.

public class TestClass {
  public String test() {
    System.out.println("test called!");
    return "test";
  }
}

//in test
TestClass mock = mock(TestClass.class);

when(mock.test()).thenReturn("mock!"); //<-- prints test called here? why? how can I switch it off?

Upvotes: 9

Views: 5127

Answers (1)

Tom Tresansky
Tom Tresansky

Reputation: 19892

The following, running under Mockito 1.9.0 and JUnit 4.8.2, does not print anything to my console:

import static org.mockito.Mockito.*;

import org.junit.Test;

public class TestNonCall {
  public class TestClass {
    public String test() {
      System.out.println("test called!");
      return "test";
    }
  }

  @Test
  public void doTest() {
    final TestClass mock = mock(TestClass.class);

    when(mock.test()).thenReturn("mock!");
  }
}

Further, if I put a breakpoint in the test() method it is never hit.

Perhaps post more code? It looks like your example is not complex enough to demonstrate the behaviour you're having problems with.

Also: are you using the latest version of Mockito?

Edit: New Thought: Are You Mocking a Final Method?

If you add a final modifier to the method you are mocking, you get the behaviour you reported.

This is because Mockito does not mock final and static methods. Instead, it delegates the calls to the real implementation.

Might your actual code be attempting to mock a final method?

If so, you can use PowerMock, which is an extension to Mockito that allows mocking final methods.

You would need to add the following annotations to your test case class:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TestClass.class)
public class TestNonCall {
  // ...
}

and mock the class using the PowerMock method in your test method:

final TestClass mock = PowerMockito.mock(TestClass.class);

then proceed as usual.

Upvotes: 9

Related Questions