0

Is it possible to test that the "innerMethod" was called without modifying the Class class?

I need to make a unit test in a separate class both scenario of the "someCondition".

The problem is that the method is void so I cannot make use of the return type. The only way would be to check if the "innerMethod" was called.

I was thinking to use Mokito verify but this method is called inside a method on an object created at runtime.

Any suggestion is most welcome.

public class Class {

     public void outerMethod(outerObj) {

          if(someCondition) {

               Object innerObj = new Object();
               innerObj.innerMethod(outerObj); 

          } else {

               //other code
          }    
}
Jasurbek
  • 2,946
  • 3
  • 20
  • 37
Victor Calin
  • 3
  • 1
  • 7
  • You could Mock the Object class, and check using Mockito – Stultuske Jul 04 '19 at 11:41
  • 1
    Possible duplicate of https://stackoverflow.com/questions/9841623/mockito-how-to-verify-method-was-called-on-an-object-created-within-a-method – A_C Jul 04 '19 at 11:47

1 Answers1

0

You can achieve that with the use of Mockito::times and Mockito::verify methods.

test setup would be as follows:

@InjectMocks
private SomeService service;

@Mock
private SomeHelper helper;

and then test that some method from the helper has been involved in the following manner:

@Test
public void testInnerHasBeenCalledOnce() throws Exception {

    service.outherMethodName(someParam);

    Mockito.verify(helper, Mockito.times(1)).innerMethodName(someParamSecond);
}
dbl
  • 1,109
  • 9
  • 17
  • @VictorCalin Could you accept the answer if you find it a match. – dbl Jul 05 '19 at 08:02
  • [What should I do when someone answers my question](https://stackoverflow.com/help/someone-answers) -> accept an answer (if it is the most appropriate though). – dbl Jul 05 '19 at 12:36