Koin-10-Testing(测试)

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 {

    // Lazy inject property
    val componentA : ComponentA by inject()

    // use it in your tests :)
    @Test
    fun `make a test with Koin`() {
        startKoin { modules(appModule) }

        // use componentA here!
    }
}

你能使用 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)
    }

    // Lazy inject property
    val componentA : ComponentA by inject()

    // use it in your tests :)
    @Test
    fun `make a test with Koin`() {
        // use componentA here!
    }
}

检查你的模块

我们可以使用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

或者

1
./gradlew checkModules --continuous

动态Mock

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)
    }

    // required to make your Mock via Koin
    @get:Rule
    val mockProvider = MockProviderRule.create { clazz ->
        Mockito.mock(clazz.java)
    }

    val componentA : ComponentA by inject()

    @Test
    fun `declareMock with KoinTest`() {
        declareMock<ComponentA> {
            // do your given behavior here
            given(this.sayHello()).willReturn("Hello mock")
        }
    }
}

开始或停止测试

请注意在每个测试之间都需要通知你的Koin实例(如果你使用 startKoin 在你的测试中)。否则,请确保对本地koin实例使用 koinApplicationstopKoin() 来停止当前的全局实例。