【问题标题】:Test EntityManager with Junit5 Kotlin使用 Junit5 Kotlin 测试 EntityManager
【发布时间】:2021-03-24 11:29:55
【问题描述】:

我正在尝试介绍 Spring JPA,但在运行测试时遇到了困难。 我的 gradle.build.kts 如下所示

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.4.0"
    id("io.spring.dependency-management") version "1.0.10.RELEASE"
    kotlin("jvm") version "1.4.10"
    kotlin("plugin.spring") version "1.4.10"
    kotlin("plugin.jpa") version "1.4.10"
}

group = "com.pluralsight"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8

repositories {
    mavenCentral()
    jcenter()
    google()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    runtimeOnly("com.h2database:h2")
    testImplementation(platform("org.junit:junit-bom:5.7.0"))
    testImplementation("org.junit.jupiter:junit-jupiter")

}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "1.8"
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

我正在使用 Junit5 作为我的测试框架。我首先需要测试的是我的 Flight Entity 是否正确创建。我没有使用@SpringRunner,因为我们在 Junit5 上,所以我执行以下操作:

package com.pluralsight.springdataoverview
import com.pluralsight.springdataoverview.entity.Flight
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.boot.test.context.SpringBootTest
import java.time.LocalDateTime
import javax.persistence.EntityManager


@SpringBootTest
@DataJpaTest
class SpringDataOverviewApplicationTests {
    @Autowired
    private val entityManager: EntityManager? = null
    @Test
    fun verifyFlighTCanBeSaved() {
        var flight = Flight()
        flight.origin = "London"
        flight.destination = "New York"
        flight.scheduledAt = LocalDateTime.parse("2011-12-13T12:12:00")
        entityManager!!.persist(flight)
        val flights = entityManager
            .createQuery("SELECT f FROM Flight f", Flight::class.java)
            .resultList
        Assertions.assertEquals(flights.first(), flight)
    }
}

我有以下红色

我缺少什么依赖项?

【问题讨论】:

  • 你能添加你的主要 Spring Boot 类吗?

标签: spring-boot kotlin junit5 entitymanager


【解决方案1】:

您有多个配置声明(这就是您的错误消息所说的)。

这是因为您在同一配置类中使用@SpringBootTest@DataJpaTest,即SpringDataOverviewApplicationTests

使用其中任何一个都可以。

【讨论】:

  • 现在错误提示“配置错误:为测试类找到了多个@BootstrapWith 声明”
  • 如果问题中提到的问题有助于解决您的问题,请接受答案。它可能会帮助其他人。
  • 现在应该可以了。检查更新的答案。
  • 不是它没有。给我你的 github 名字,我会让你访问我的 github 链接
猜你喜欢
  • 2020-08-25
  • 1970-01-01
  • 2022-01-27
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 2023-04-11
  • 2019-11-01
相关资源
最近更新 更多