I am beginer in unit testing. I use JUnit and Mockito. This is one example method which I want to test.
public Void getPeopleNumbersList(List<Aggregate<Person>> aggregateList) {
for (List<Person> person : peopleList) {
List<PhoneNumber> phoneNumbersList = getPhoneNumbers(person);
for (PhoneNumber phoneNumber : phoneNumbersList) {
//Some functions to do some DB operations.
DynamoDB.update(phoneNumber); // Just an example
}
}
}
How do I test if operation/function (here, it is update call) is called for each phone number of each person in Mockito?
CodePudding user response:
It depends on what your method should do. The example you provided is hard to test since you are calling a static class. I assume you can get the Reference to the DB Operation in your test class. If so then I would mock your Database reference with mockito:
@InjectMocks
private YourClassToTest classUnderTest; // the class where the
@Mock
private Database database;
void someTest(){
List<Aggregate<Person>> aggregateList = new ArrayList<>();
classUnderTest.getPeopleNumbersList();
verify(database, times(0)).update(any());
}
CodePudding user response:
To get inside for loops, you should send in an actual list. Let's say the class you're testing is ClassUnderTest. Once you're in the for loop, if you can continue with the normal execution of getPhoneNumbers() then it would be great otherwise mock it.
@Test
public void test()
{
List<Aggregate<Person>> list = new ArrayList<>();
list.add(value1);
list.add(valuen);
List<PhoneNumber> list_phone = new ArrayList<>();
list_phone.add(value1);
list_phone.add(valuen);
ClassUnderTest object = new ClassUnderTest();
ClassUnderTest spy = spy(object);
when(spy.getPhoneNumbers(person)).thenReturn(list_phone);
// .....
// mock the operations inside
// the method DynamoDB.update(phoneNumber);
// .....
object.getPeopleNumbersList(list);
}