共计 2075 个字符,预计需要花费 6 分钟才能阅读完成。
提醒:本文最后更新于2023-05-27 19:05,文中所关联的信息可能已发生改变,请知悉!
https://start.insert-koin.io/#/getting-started/testing
开始
Koin in 5 minutes (5分钟快速入手Koin)
Getting Started (开始)
Koin-test 项目能提供给你轻量但是强大的工具来测试你的Koin应用程序。
只要用 KoinTest 标记你的测试类,你就可以解锁KoinComponent &测试特性:
by inject() – 延迟注入一个实例
get() – 检索一个实例
按照以下来定义:
1 2 3 4
val appModule = module { single { ComponentA() } }
你就能像下面这样来写一个测试:
1 2 3 4 5 6 7 8 9 10 11 12 13
class MyTest : KoinTest { val componentA : ComponentA by inject() @Test fun `make a test with Koin`() { startKoin { modules(appModule) } } }
你能使用 KoinTestRule JUnit规则来开启或关闭你的Koin上下文:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class MyTest : KoinTest { @get:Rule val koinTestRule = KoinTestRule.create { modules(appModule) } val componentA : ComponentA by inject() @Test fun `make a test with Koin`() { } }
我们可以使用Koin Gradle插件来让我们运行我们的模块检查:
1 2 3 4 5 6 7 8 9 10
buildscript { repositories { jcenter() } dependencies { classpath "org.koin:koin-gradle-plugin:$koin_version" } } apply plugin: 'koin'
按照如下来写检查测试:
使用一个JUnit CheckModuleTest 类别
通过 checkModules { } API来测试模块
1 2 3 4 5 6 7 8
@Category(CheckModuleTest::class) class ModuleCheckTest : AutoCloseKoinTest () { @Test fun checkModules () = checkModules { modules(appModule) } }
让我们通过Gradle命令来检查我们的模块:
或者
1
./gradlew checkModules --continuous
Once you have tagged your class with KoinTest interface, you can use the declareMock function to declare mocks & behavior on the fly:
一旦你用 KoinTest 接口标记了你的类,你就能使用 declareMock 函数来动态声明mocks(模拟)或者behavior(行为):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
class MyTest : KoinTest { @get:Rule val koinTestRule = KoinTestRule.create { modules(appModule) } @get:Rule val mockProvider = MockProviderRule.create { clazz -> Mockito.mock(clazz.java) } val componentA : ComponentA by inject() @Test fun `declareMock with KoinTest`() { declareMock<ComponentA> { given(this .sayHello()).willReturn("Hello mock" ) } } }
请注意在每个测试之间都需要通知你的Koin实例(如果你使用 startKoin 在你的测试中)。否则,请确保对本地koin实例使用 koinApplication 或 stopKoin() 来停止当前的全局实例。