[英]Is it a right case for Mockito spy?
Let's say I have a class 假设我有一堂课
class SomeClass
{
public void methodA()
{}
public void methodB()
{}
public void someMethod()
{
methodA();
methodB();
}
}
I would like to test behavior of someMethod() with Mockito. 我想用Mockito测试someMethod()的行为。
The only way I could think of is using spy(); 我能想到的唯一方法是使用spy();
Something like 就像是
SomeClass someClass = spy(new SomeClass());
someClass.someMethod();
InOrder inOrder = inOrder(someClass);
inOrder.verify(someClass).methodA();
inOrder.verify(someClass).methodB();
I'm new to the mockito and documentation says 我是mockito的新手,文档说
"Real spies should be used carefully and occasionally, for example when dealing with legacy code." “应该谨慎使用真正的间谍,例如在处理遗留代码时。”
So maybe I'm missing something and there is better (right) way to verify that methodA and methodB were called without explicitly calling them in the test case. 所以也许我错过了一些东西,并且有更好的(正确的)方法来验证methodA和methodB是否被调用而没有在测试用例中显式调用它们。
Thanks. 谢谢。
Yes, spy()
is fit for your purpose. 是的,
spy()
适合你的目的。 The warning is due to the fact that real methods are invoked, and hence you can get unexpected results (for example - real money being withdrawn from a bank account) 警告是由于调用了真实的方法,因此您可能会得到意想不到的结果(例如 - 从银行账户中提取真钱)
If your code needs spy for unit testing - something wrong. 如果你的代码需要间谍进行单元测试 - 那就错了。 Spy is a first sign of a code smell.
间谍是代码气味的第一个标志。 You have two options to avoid it in your example:
在您的示例中,您有两种方法可以避免它:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.