简体   繁体   中英

Mockito doReturn if method of a object with certain class is called

If I have a object MyObject, I want to return some value if certain method of that object is called. For example something like this:

doReturn(someValue).when(Mockito.any(MyObject.class)).getSomeValue();

I have tried it like that, but it does not works :

org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to when() is null!

You need to use Mockito.mock(MyObject.class) to create a mock of your object.

Currently you're using Mockito#any which is a parameter matcher used to define behavior on a mock when a stubbed method is called for any given parameter.

@Test
public void testMock() throws InterruptedException {
    MyObject myObjectMock = Mockito.mock(MyObject.class);
    doReturn(2).when(myObjectMock).getSomeValue();

    System.out.println(myObjectMock.getSomeValue()); // prints 2
}

private class MyObject {
    public int getSomeValue() {
        return 1;
    }
}

Alternatively, you can use Mockito annotations:

@RunWith(MockitoJUnitRunner.class)
public class YourTestClass {
  @Mock 
  MyObject myObjectMock

saves you from manually mocking that object within your setup or test methods.

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