简体   繁体   English

模拟验证

[英]mockito mock verify

//Let's import Mockito statically so that the code looks clearer
import static org.mockito.Mockito.*;

//mock creation
List mockedList = mock(List.class);

//using mock object
mockedList.add("one");
mockedList.clear();

//verification
verify(mockedList).add("one");
verify(mockedList).clear();

I don't understand what is the point of this construct? 我不明白这种结构的意义是什么? How does it help? 它有什么帮助? How is it different from just calling the functions? 它与仅调用函数有何不同?
The documentation is rather thin. 该文档很薄。
Thank you 谢谢

When you do mockedList.add("one"); 当您mockedList.add("one"); its performing the operation on the mocked object as same time it remembers your operation. 它会在记住您的操作的同时对mocked object执行操作。 So when you do verify(mockedList).add("one"); 因此,当您verify(mockedList).add("one"); , it verifies the add was called on mockedList with argument one . ,它验证add被称为上mockedList与争论one

Hope you get the difference. 希望你能有所作为。

You wish to test that some method Foo of class A calls some method Bar on an object of class B. In other words, you're testing class A. During your test, you make a mock of class B. Then you pass this mock object to class A somehow (depending on how class A actually works). 您希望测试类A的某些方法Foo在类B的对象上调用了方法Bar 。换句话说,您正在测试类A。在测试过程中,您对类B进行了模拟。然后传递此模拟以某种方式反对A类(取决于A类的实际工作方式)。 When your test runs the Foo method of class A, you are expecting the Bar method to get called on your mock of class B. By calling verify for the Bar method, after the test of the Foo method, you can check that the Foo method is actually working correctly - that it calls Bar . 当您的测试运行Foo类A的方法,你期望的Bar法得到您的B级的模拟称为通过调用verifyBar法,试验后Foo的方法,你可以检查Foo方法实际上工作正常-称为Bar

the verify method of mockito is verify the method invoke times,if the invoke time is 1,we can omit this parameter, see the source code of Mockito Line 1473 Mockito的verify方法是验证方法的调用时间,如果调用时间为1,则可以省略此参数,请参见Mockito Line 1473的源代码

public static <T> T verify(T mock) {
    return MOCKITO_CORE.verify(mock, times(1));
}

so you code 所以你编码

verify(mockedList).add("one");
//is the same as
verify(mockedList,times(1)).add("one");

is indeed to verify the add method's executed once 确实是要验证add方法的执行一次

Indeed in your example it's obvious, but main idea of verifying methods calls appear during real code testing - imagine that some code performs method call like: 确实在您的示例中这很明显,但是验证方法调用的主要思想出现在实际的代码测试期间-想象一些代码执行方法调用,例如:

class A{
 ....
 service.doSomething(<some arguments>)
 ....
}

In order to test it you'll pass mock service object, but sometimes you want to verify particular arguments values passed for that call (or number of calls), so you'll use verify like in your example. 为了测试它,您将传递模拟服务对象,但有时您想验证为该调用传递的特定参数值(或调用次数),因此您将像示例中那样使用verify。

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

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