Spring Reactive 单元测试

测试挂起函数

测试方法通过 runBlock 包裹挂起函数:

@Test
fun test(): Unit = runBlocking {
    // ...
}

注入测试依赖

  1. 通过在依赖对象前添加 @Autowired 注解注入:
@SpringBootTest
class UserRepositoryTest(
    @Autowired private val mongoTemplate: ReactiveMongoTemplate
) {
    // ...
}
  1. 使用在测试类中添加 @TestConstructor 注解注入:
@SpringBootTest
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
class UserRepositoryTest(
    private val mongoTemplate: ReactiveMongoTemplate
) {
    // ...
}

在非静态方法中使用 @AfterAll@BeforeAll

Spring Projects in Kotlin == Spring Framework

默认情况下 Junit5 必须在静态方法中使用 @AfterAll@BeforeA 如:

class ApplicationTest {
    companion object {
        @JvmStatic
        @BeforeAll
        fun beforeAll() {
            // ...
        }
 
        @JvmStatic
        @AfterAll
        fun afterAll() {
            // ...
        }
    }
}

这样对于需要引入依赖的 Spring 程序来说没法使用,可以增加@TestInstance 注解解决:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ApplicationTest {
    @BeforeAll
    fun beforeAll() {
        // ...
    }
 
    @AfterAll
    fun afterAll() {
        // ...
    }
}