JUnit 4 → JUnit 5 + Kotlin

JUnit 4 → JUnit 5 + Kotlin

老写法(Java + JUnit 4)

java 复制代码
@RunWith(MockitoJUnitRunner.class)
public class ItemViewModelTest {

    @Mock ApiService apiService;
    @Captor ArgumentCaptor<String> captor;
    private ItemViewModel viewModel;

    @Before
    public void setUp() {
        viewModel = new ItemViewModel(apiService);
    }

    @Test
    public void loadItems_success() {
        List<Item> items = Arrays.asList(new Item(1, "test"));
        when(apiService.loadItems()).thenReturn(items);

        viewModel.loadItems();

        verify(apiService).loadItems();
        assertEquals(1, viewModel.getItems().getValue().size());
    }

    @Test(expected = IOException.class)
    public void loadItems_error() throws Exception {
        when(apiService.loadItems()).thenThrow(new IOException());
        viewModel.loadItems();
    }
}

问题在哪里

@RunWith 只能用在一个 Test 类上,无法组合多个 Runner。@Test(expected = ...) 无法精确验证异常信息,且只能检查方法结束时是否抛了异常,中间抛了也算通过。

新写法(JUnit 5 + Kotlin)

kotlin 复制代码
@ExtendWith(MockKExtension::class)
class ItemViewModelTest {

    @MockK lateinit var apiService: ApiService
    private lateinit var viewModel: ItemViewModel

    @BeforeEach
    fun setUp() {
        viewModel = ItemViewModel(apiService)
    }

    @Test
    fun `load items returns data on success`() = runTest {
        val items = listOf(Item(1, "test"))
        coEvery { apiService.loadItems() } returns items

        viewModel.loadItems()

        coVerify { apiService.loadItems() }
        assertEquals(1, viewModel.items.value?.size)
    }

    @Test
    fun `load items handles error`() = runTest {
        coEvery { apiService.loadItems() } throws IOException("网络错误")

        assertThrows<IOException> {
            runBlocking { viewModel.loadItems() }
        }
    }
}

一句话注意

JUnit 5 的 @ExtendWith 可以组合多个 Extension(相当于 JUnit 4 的多个 Runner 组合)。Kotlin 中测试方法名可以用反引号括起来写中文或完整的英文描述,比 Java 的 camelCase 方法名可读性高。

runTest 是 kotlinx-coroutines-test 提供的测试协程作用域,自动跳过 delay 等挂起时间,测试不会真的等待。


Java Android 老项目迁移系列,持续更新中。

相关推荐
赵广陆40 分钟前
Spring AI的聊天模型
java·人工智能·spring
IT 小阿姨(数据库)1 小时前
K8s v1.24.17 完整搭建文档(CentOS7 + containerd1.6.33 + Calico)
java·容器·kubernetes
lhldsg1 小时前
全民健身解决方案:从共享球场到智能运营的技术实践
java·大数据·开发语言·需求分析
vipxieliang1 小时前
ValidX时间注解完全指南:10种时间验证注解详解
java·后端
字节暗面1 小时前
四款 APP 加固强度测评:让 AI 拆了四个包,结果有点出乎意料
android·逆向工程·加固
雨辰AI2 小时前
openGauss 生产运维避坑指南|适配信创项目改造核心难点
java·运维·后端
网安蟹佬霸2 小时前
蓝队防御实战:SIEM与SOAR构建安全运营中心(万字详解+实战配置)
android·安全·web安全·网络安全·网安
名字还没想好☜2 小时前
Java 21 switch 模式匹配实战:sealed 接口 + record 替代 if-instanceof 链
java·人工智能·后端·python·spring
devilnumber2 小时前
Java 30 组高频技术 / 知识点多角度对比
java·开发语言
摇滚侠2 小时前
《SpringBoot 3:入门与应用实战》第 6 章 Spring Boot 最佳实践 阅读笔记 10
java·spring boot·笔记