简体   繁体   English

使用 Mockito.when 方法返回调用其他方法的方法

[英]Using Mockito.when method for method that calls other method in return

I'm trying to test my class but it seems that my Mockito.when() doesn't work, and I getting a "example" instead "another example".我正在尝试测试我的 class 但似乎我的 Mockito.when() 不起作用,我得到一个“示例”而不是“另一个示例”。 Any ideas?有任何想法吗?

public class ExampleClass {
    public String create(String example){
         return doSth();
    }

    public String doSth(){
         return "example";
    }
}
public class ExampleClassTest {
    @Mock
    ExampleClass exampleClassMock;

    public void createTest(){
        when(exampleClassMock.doSth()).thenReturn("another example");

        assertEquals(exampleClassMock.create("x"), "another example");
    }
}

First of all, don't forget to place @Test annotation onto your test methods and @RunWith(MockitoJUnitRunner.class) onto the test class.首先,不要忘记将@Test注释放在您的测试方法上,并将@RunWith(MockitoJUnitRunner.class)放在测试class 上。

Second, if you need to test the method of some class, and inside of it the other method of the same class is called which you want to mock, then you need to use @Spy:其次,如果您需要测试一些 class 的方法,并且在其中调用您要模拟的相同 class 的另一个方法,那么您需要使用@Spy:

@RunWith(MockitoJUnitRunner.class)
public class ExampleClassTest {

    @Spy
    ExampleClass exampleClassMock;

    @Test
    public void createTest() {
        when(exampleClassMock.doSth()).thenReturn("another example");

        assertEquals(exampleClassMock.create("x"), "another example");
    }
}

See docs for spying.请参阅docs进行间谍活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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