Junit And Mockito, Capturing method call on passed argument

706 Views Asked by At

I am relatively new to Mockito and Junit in Java. How can I capture or verify the interaction on the argument passed to function that I am testing. Ex-- Main class

public class A{

 public void setValues(Person p){
  p.setFirstName('Lucky');
  p.setLastName('Singh');

// Some more code
 }
}

Test class

class Test {

@InjectMocks
A classUnderTest;

@Test 
public void tests(){
  classUnderTest.setValues(new Person());
// What to do next to verfiy that the setFirstName and setLastName where really called on Person Object as setValues have void return type??
}
}

Now i want to test this setValues method with void return type. I know if return type would have been Person I could have used assert. But I cannot change method defination. So I want to verify that the call to setFirstName and setlastName is made.
I am using pit-test and the mutation removed call to setFirstName and setlastName is not getting KILLED.
How can I achieve this ??

1

There are 1 best solutions below

1
On BEST ANSWER

You can inject a spy for your Person class and then verify if the methods are called as follows:

class Test {
  @Spy
  Person person = new Person();

  @InjectMocks
  A classUnderTest;

  @Test 
  public void tests(){
    classUnderTest.setValues(person);

    // You can now verify if the methods setFirstName and setLastName where really called on Person
    verify(person, times(1)).setFirstName(isA(String.class));
    verify(person, times(1)).setLastName(isA(String.class));
  }
}

A spy will wrap an existing instance, in your case Person. It will still behave in the same way as the normal instance, the only difference is that it will also be instrumented to track all the interactions with it so that you can actually verify on the methods that are called.