Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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). 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.

like image 772
Perlos Avatar asked Jan 06 '12 08:01

Perlos


People also ask

How do you verify a method called in Mockito?

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.

How do you mock another method that is being tested in the same class?

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.

Which method in Mockito verifies that no interaction has happened with a mock in Java?

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.

What is Spy method in Mockito?

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.


1 Answers

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(); 
like image 164
denis.solonenko Avatar answered Oct 25 '22 04:10

denis.solonenko