Java – How to verify if method was called from other with same class by mockito

javamockito

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). Basically call getPrice(int) as normal and 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();
    }
}

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.

Best Solution

You would need a spy, not a mock A:

    A a = Mockito.spy(new A(1,1));
    a.getPrice(2);
    verify(a, times(1)).getPriceForOne();