如何验证方法是否通过mockito从具有相同类的其他方法调用

Per*_*los 41 java mockito

我想测试一些在同一个类中调用其他人的方法.它基本上是相同的方法,但参数较少,因为数据库中有一些默认值.我在这上面展示

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我想测试是否在调用方法getPrice(int)时调用了方法getPriceForOne().基本上调用普通方法getPrice(int)和mock 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

考虑一下,我有一个更复杂的文件,这个文件是其他人的实用工具,必须全部在一个文件中.

den*_*nko 63

你需要一个间谍,而不是一个模拟A:

    A a = Mockito.spy(new A(1,1));
    a.getPrice(2);
    verify(a, times(1)).getPriceForOne();
Run Code Online (Sandbox Code Playgroud)

  • ** getPriceForOne **应该具有一些任意参数吗? (3认同)