Junit 5单测用法

匿名回调函数

@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());
    }

JUnit 5 是 Java 编程语言的单元测试框架,它是 JUnit 团队开发的最新版本。JUnit 5 提供了一套强大的工具和功能,用于编写和执行单元测试。下面是 JUnit 5 单元测试的一些重要特性和用法: 1. 注解驱动:JUnit 5 使用注解来标记测试方法和测试类。常用的注解包括 `@Test`、`@BeforeEach`、`@AfterEach` 等。 2. 断言方法:JUnit 5 提供了丰富的断言方法,用于验证测试结果是否符合预期。例如,`assertEquals()`、`assertTrue()`、`assertNotNull()` 等。 3. 参数化测试:JUnit 5 支持参数化测试,可以通过 `@ParameterizedTest` 注解来定义参数化测试方法,并使用 `@ValueSource`、`@CsvSource` 等注解提供测试参数。 4. 嵌套测试:JUnit 5 允许在一个测试类中嵌套其他测试类,以更好地组织和管理测试代码。 5. 扩展模型:JUnit 5 引入了扩展模型,通过实现扩展接口可以自定义测试生命周期、测试报告、参数解析等行为。 6. 并发执行:JUnit 5 支持并发执行测试,可以通过 `@Execution` 注解来配置并发策略。 7. 动态测试:JUnit 5 允许在运行时动态生成测试用例,通过 `DynamicTest` 接口和 `@TestFactory` 注解实现。 8. 条件测试:JUnit 5 提供了条件测试的功能,可以根据条件来决定是否执行某个测试方法。 以上是 JUnit 5 单元测试的一些重要特性和用法。如果你还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值