class A {
public void foo(OtherClass other) {
SomeData data = new SomeData("Some inner data");
other.doSomething(data);
}
}
现在如果你想检查内部数据,你可以使用捕获器:
// Create a mock of the OtherClass
OtherClass other = mock(OtherClass.class);
// Run the foo method with the mock
new A().foo(other);
// Capture the argument of the doSomething function
ArgumentCaptor<SomeData> captor = ArgumentCaptor.forClass(SomeData.class);
verify(other, times(1)).doSomething(captor.capture());
// Assert the argument
SomeData actual = captor.getValue();
assertEquals("Some inner data", actual.innerData);
public class PersonService {
private PersonRepository personRepository;
public void setPersonRepository(final PersonRepository personRepository) {
this.personRepository = personRepository;
}
public void savePerson(final String name) {
this.personRepository.save(name.toUpperCase().trim());
}
}
public class PersonRepository {
public void save(final String person) {
System.out.println(".. saving person ..");
}
}
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
class PersonServiceTest {
@Test
void testPersonService() {
// Create the repository mock
final PersonRepository personRepositoryMock = mock(PersonRepository.class);
// Create the service and set the repository mock
final PersonService personService = new PersonService();
personService.setPersonRepository(personRepositoryMock);
// Save a person
personService.savePerson("Mario ");
// Prepare an ArgumentCaptor to capture the value passed to repo.saveMethod
final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// Capture the argument passed in the unique method invocation
verify(personRepositoryMock, times(1)).save(captor.capture());
// Check if the captured value is the expected one
final String capturedParameter = captor.getValue();
assertEquals("MARIO", capturedParameter);
}
}