spring-boot - 如何在单元测试中从依赖注入(inject)容器中获取实例?

标签 spring-boot kotlin dependency-injection

假设我有以下类(class):

import com.fasterxml.jackson.databind.ObjectMapper

class Foo(private val jsonMapper: ObjectMapper) {
    // ...
}

以及相应的测试:
import com.fasterxml.jackson.databind.ObjectMapper

@RunWith(MockitoJUnitRunner::class)
class FooTest {

    private val jsonMapper = ObjectMapper().findAndRegisterModules()

    private lateinit var foo: Foo

    @Before
    fun makeFoo() {
        foo = Foo(jsonMapper)
    }
}

我的问题是我必须调用 findAndRegisterModules (拥有jsr310 支持等)手动。我更愿意让 Spring Boot 决定如何构建我的依赖项。

但是由于 java.lang.Exception: Test class should have exactly one public zero-argument constructor 导致以下失败:
import com.fasterxml.jackson.databind.ObjectMapper

@RunWith(MockitoJUnitRunner::class)
class FooTest(private val jsonMapper: ObjectMapper) {

    private val foo = Foo(jsonMapper)
}

那么,处理这种情况的正确方法是什么?

最佳答案

您的测试失败,因为 JUnit4 测试需要有一个无参数构造函数。

此外,您的测试没有使用 Spring,因为您使用的是 @RunWith(MockitoJUnitRunner::class) 注释。此运行程序允许初始化您的 Mock 对象并将它们注入(inject)您的测试对象 (Javadoc)。

如果您想使用 Spring 构建您的测试主题及其依赖项,您需要使用一组不同的注释(查看 tutorial 了解更多详细信息):

@RunWith(SpringRunner::class)
@SpringBootTest 
class FooTest {
   @Autowired
   lateinit var foo: Foo
}

关于spring-boot - 如何在单元测试中从依赖注入(inject)容器中获取实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56215354/

相关文章:

spring-boot - HystrixCommand 注解在用于包装 Spring Integration Gateway 调用时不起作用

android - Mutidex和Kotlin

java - Spring Boot 可选的多部分 POST 请求

spring-boot - 在类型 'isLPG' 的对象上找不到属性或字段 'com.rentautosofia.rentacar.bindingModel.CarBindingModel' - 可能不是公共(public)的?

kotlin - Reactor - 只为慢速消费者保留/处理最新值

kotlin - Kotlin 泛型中列表和可变列表的区别

java - java中如何结合mock和DI?

c# - Autofac 注入(inject)通用接口(interface)的 IEnumerable

dependency-injection - 统一: Replace registered type with another type at runtime

spring-boot - 云类型转换厂 : Spring boot vs WAR file