简体   繁体   English

正确使用Mockito.verify

[英]Proper usage of Mockito.verify

I'm new to unit testing and i had a simple question regarding the usage of verify method used in Mockito. 我是单元测试的新手,我对Mockito中使用的verify方法的使用有一个简单的问题。 here's the class i used for testing. 这是我用于测试的类。

public class Foo{
int n = 0;
void addFoo(String a){
    if(a == "a")
    add(1);
}

protected void add(int num){
    n =1;
}

public int get(){
    return n;
}

} }

And here's my Unit test. 这是我的单元测试。

public class FooTest {
@Mock Foo f;

@Test
public void test() {
    MockitoAnnotations.initMocks(this);
    f.addFoo("a");

    //Passes
    Mockito.verify(f).addFoo("a");

    //Fails
    Mockito.verify(f).add(1);
}

} }

And i get a 我得到了一个

   Wanted but not invoked:
f.add(1);
-> at FooTest.test(FooTest.java:22)

However, there were other interactions with this mock:
-> at FooTest.test(FooTest.java:16)

exception. 例外。

How do you verify that add(int num) is called ? 你如何验证add(int num)被调用?

I think you misunderstood the point of verify . 我想你误解了verify点。 In your test, Foo f is a mock object - Foo 's internal implementation is ignored, and only the behavior you recorded on it (using when(f.someMethod().thenXXX ) would happen. 在你的测试中, Foo f是一个模拟对象 - 忽略了Foo的内部实现,只有你在其上记录的行为(使用when(f.someMethod().thenXXX )会发生。

The point of mocking and verifying is to test interactions while ignoring the internal implementation. 模拟和验证的关键是测试交互,而忽略内部实现。 In this example, you would probably have another class that uses Foo , and you'd want to test whether it invokes the correct methods of the given Foo instance. 在这个例子中,您可能有另一个使用 Foo类,并且您想测试它是否调用给定Foo实例的正确方法。

Quick example: 快速举例:

Assume you have a class the uses the Foo class you presented in your question: 假设您有一个类使用您在问题中提供的Foo类:

public class FooUser {
    private Foo f;

    public void setFoo(Foo f) {
        this.f = f;
    }

    public Foo getFoo() {
        return f;
    }

    public void addToFoo(String string) {
        f.add(string);
    }
}

Now, you'd want to test that FooUser#addToFoo(String) indeed invokes the correct add(String) method of Foo : 现在,您要测试FooUser#addToFoo(String)确实调用了Foo的正确add(String)方法:

@RunWith (MockitoJUnitRunner.class)
public class FooUserTest {
    @Mock Foo f;
    FooUser fUser;

    @Before
    public void init() {
        fUser = new FooUser();
        fUser.setFoo(f);
    }

    @Test
    public void test() {
        fUser.addToFoo("a");
        Mockito.verify(f).addFoo("a");
    }

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

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