我正在为具有带有break语句的while循环的现有代码编写Junit测试用例(带有jupitar的Junit 5)。
public int deleteRecords(int batchsize) {
//some code here
int totalDeletedRecords = 0;
while(true) {
int deleted = deleteRecord();
if (deleted == 0) { //means no record found to delete
break;
}
totalDeletedRecords += deleted;
}
}
private int deleteRecord() {
List<User> usersList = repository.findAll(); //get the records from the database;
if (CollectUtils.isEmpty()) {
return 0;
}
//then deleting the total records batch wise
//construct list with ids and pass that to delete method
repository.delete(List of ids);
return userList.size();
}
我的 Junit 测试用例,
@Test
public void testDeleteRecordSuccess() {
//mock repository call
User user = User.builder().name("xyz").build();
when(repository.findAll()).thenReturn(Arrays.asList(user));
doNothing().when(repository).delete(anyList());
int deleted = service.deleteRecords(1000);
assertEquals(1, deleted);
}
根据模拟,记录的大小始终为 1 并且循环执行无限。循环需要停止,并且所有代码行都应该覆盖。
让我知道如何在这种情况下模拟存储库调用。
也许你应该让
repository.findAll()
返回两次来测试循环。
@Test
public void testDeleteRecordSuccess() {
// Create a test user
User user = User.builder().name("xyz").build();
// Create two lists, one with the user and one empty
List<User> listWithUsers = Arrays.asList(user);
List<User> emptyList = Collections.emptyList();
// Mock repository calls
// First call to findAll() will return the list with users, second call will return an empty list
when(repository.findAll()).thenReturn(listWithUsers, emptyList);
// Mock the .delete() call to do nothing
doNothing().when(repository).delete(anyList());
// The service call should now proceed as expected, without any infinite loop
int deleted = service.deleteRecords(1000);
// Verify that records were 'deleted'
assertEquals(1, deleted);
// Verify calls to mock object
verify(repository, times(2)).findAll();
verify(repository, times(1)).delete(anyList());
}