匿名回调函数
@ExtendWith(MockitoExtension.class)
class SftpTransferRetrySchedulerTest {
@Mock
private RemittanceFileUploadRetryRepository retryRepository;
@Mock
private SftpUploadService sftpUploadService;
@InjectMocks
private SftpTransferRetryScheduler scheduler;
// 1.注入ArgumentCaptor对象,泛型为类中使用的匿名回调函数,多个的话就注入多个ArgumentCaptor对象
@Captor
private ArgumentCaptor<UploadCallback> callbackCaptor;
private RemittanceFileUploadRetry retry;
@BeforeEach
void setUp() {
retry = new RemittanceFileUploadRetry();
retry.setId(1L);
retry.setBatchId("batch123");
retry.setCompanyName("companyA");
retry.setRetriedCount(0);
retry.setLastRetryStatus(RemittanceFileRetryStatus.FAILED);
}
@Test
void testUploadFileFailed() {
when(retryRepository.listNeedToRetry(anyString())).thenReturn(List.of(retry));
//2. 在哪里使用回调函数的地方,capture(),埋点
// callback function junit test
when(sftpUploadService.uploadRemittanceFile(anyString(), anyString(), callbackCaptor.capture())).thenReturn(false);
//3.调用需要覆盖单测的方法
scheduler.run();
//execute callback
//4. callbackCaptor.getValue() 拿到回调函数对象
UploadCallback callback = callbackCaptor.getValue();
//5.手动执行
callback.onFailed("1",1,"1");
assertEquals(RemittanceFileRetryStatus.FAILED, retry.getLastRetryStatus());
assertEquals(1, retry.getRetriedCount());
}
}
创建临时文件
public class TempFilesJUnit5Test {
/* This directory and the files created in it will be deleted after
* tests are run, even in the event of failures or exceptions.
*/
@TempDir
Path tempDir;
@Test
public void test() throws InvalidPathException {
Path path1 = tempDir.resolve( "testfile1.txt" );
File tmpfile = path1.toFile()
...
}
...
Working and unit testing with temporary files in Java (oracle.com)
Mock静态方法
@Test
void testUploadRemittanceFileSuccess2() throws Exception {
when(baseProcessorRepository.countBatchFilesToday(anyString())).thenReturn(0);
when(brsRemittanceRepository.findAllByBatchId(anyString())).thenReturn(remittances);
ArgumentCaptor<String> filePathCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<List<String>> contentCaptor = ArgumentCaptor.forClass(List.class);
try (MockedStatic<FileUtils> mockedFileUtils = Mockito.mockStatic(FileUtils.class)) {
mockedFileUtils.when(() -> FileUtils.writeToFile(any(), any()))
.thenThrow(new IOException("Failed to write to file"));
boolean result = sftpUploadService.uploadRemittanceFile("1", COMPANY_NAME, uploadCallback);
assertTrue(result);
// verify the method has been called (optional)
mockedFileUtils.verify(() -> FileUtils.writeToFile(filePathCaptor.capture(), contentCaptor.capture()));
}
}
Mock无返回值的方法
@Test
void testUploadRemittanceFileFailure() throws Exception {
when(baseProcessorRepository.countBatchFilesToday(anyString())).thenReturn(1);
when(brsRemittanceRepository.findAllByBatchId(anyString())).thenReturn(remittances);
// void mehod
doThrow(new RuntimeException()).when(jschSftpService).uploadFile(any(File.class), anyString());
boolean result = sftpUploadService.uploadRemittanceFile("1", COMPANY_NAME, uploadCallback);
assertFalse(result);
verify(uploadCallback, times(1)).onFailed(any(), any(), any());
}