我想测试一些在同一个类中调用其他方法的方法。它们基本上是相同的方法,但具有不同数量的参数,因为数据库中有一些默认值。我在这个上显示
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;
}
}
所以我想测试调用getPrice(int)方法时是否调用了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();
}
}
请记住,我有一个更复杂的文件,它是其他人的实用程序,它们必须都在一个文件中。
最佳答案
你需要一个 spy ,而不是一个模拟 A:
A a = Mockito.spy(new A(1,1));
a.getPrice(2);
verify(a, times(1)).getPriceForOne();
关于java - 如何通过mockito验证是否从其他具有相同类的方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8755449/