[英]How to verify if method was called from other with same class by mockito
I want to test some methods that call others in the same class.我想测试一些调用同一类中其他方法的方法。 They are basically the same methods, but with different numbers of arguments because there are some default values in a database.
它们基本上是相同的方法,但参数数量不同,因为数据库中有一些默认值。 I show on this
我显示在这个
public class A{
Integer quantity;
Integer price;
A(Integer q, Integer v){
this quantity = q;
this.price = p;
}
public Float getPriceForOne(){
return price/quantity;
}
public Float getPrice(int quantity){
return getPriceForOne()*quantity;
}
}
So I want to test if the method getPriceForOne() was called when calling the method getPrice(int).所以我想测试在调用方法getPrice(int)时是否调用了方法getPriceForOne()。 Basically call getPrice(int) as normal and mock getPriceForOne.
基本上正常调用 getPrice(int) 并模拟 getPriceForOne。
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
....
public class MyTests {
A mockedA = createMockA();
@Test
public void getPriceTest(){
A a = new A(3,15);
... test logic of method without mock ...
mockedA.getPrice(2);
verify(mockedA, times(1)).getPriceForOne();
}
}
Please keep in mind that I have a much more complicated file that's a utility for others and they must all be in one file.请记住,我有一个更复杂的文件,它是供其他人使用的实用程序,它们必须都在一个文件中。
You would need a spy, not a mock A:你需要一个间谍,而不是一个模拟 A:
A a = Mockito.spy(new A(1,1));
a.getPrice(2);
verify(a, times(1)).getPriceForOne();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.