简体   繁体   中英

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, ie 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.

eg

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM