如何在用 Kotlin 编写的 JUnit 5 测试 class 中注入 Spring bean?

How to inject a Spring bean in a JUnit 5 test class written in Kotlin?

我尝试使用 JUnit 5 和 Spring Boot 在 Kotlin 项目中测试一些东西,但是我无法在我的测试中注入一个 bean class。

我尝试了很多不同的注解,但是注入神经元起作用了...

这是我的测试 class:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@ExtendWith(SpringExtension::class)
class FooTest {

   @Autowired
   lateinit var repo: BarRepository

   @BeforeAll
   fun setup() {
   }

   @Test
   fun testToto() {
   }
}

使用此注释组合,代码会引发以下异常: java.lang.NoClassDefFoundError:org/springframework/boot/context/properties/source/ConfigurationPropertySource。 而且我实际上无法找到这个异常来自哪里......我试图对这个异常进行一些研究,但我没有找到任何令人满意的东西......

我猜你的依赖有问题。如果您从 https://start.spring.io/#!language=kotlin 生成一个新的 Spring Boot Kotlin 项目,然后按如下方式自定义您的依赖项,它将按预期工作:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-reflect</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib-jdk8</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <artifactId>junit</artifactId>
                <groupId>junit</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

另请注意,您不需要指定 @ExtendWith(SpringExtension::class),因为从 Spring Boot 2.1 开始,@SpringBootTest 已经使用此注释进行了元注释。

我终于找到了解决问题的方法。我的 Spring 引导版本最初是“1.5.3”,所以我将其 pom.xml 更改为“2.0.2”版本。现在我的测试 运行 正常,并且我的 bean 已按预期正确注入。这是我的修改部分 pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
    <relativePath/>
</parent>

修改版本后一切正常。 以下是使用 Junit 测试的有用依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <artifactId>junit</artifactId>
            <groupId>junit</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <scope>test</scope>
</dependency>