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.
Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.
We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.
Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.
A Mockito spy is a partial mock. We can mock a part of the object by stubbing few methods, while real method invocations will be used for the other. By saying so, we can conclude that calling a method on a spy will invoke the actual method, unless we explicitly stub the method, and therefore the term partial mock.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With