gpt4 book ai didi

java - @DirtiesContext 不适用于 Spring Boot 和 Kotlin

转载 作者:行者123 更新时间:2023-11-30 02:13:45 28 4
gpt4 key购买 nike

我正在尝试在 Spring Boot 中运行一些集成测试。为此,我认为我们应该在每次测试运行后使用 @DirtiesContext 来清理数据库。

我现在尝试了几种方法,但效果都一样。

这是我的设置:

  • Spring Boot 1.5.10.RELEASE
  • SQL Server 2016
  • Kotlin 1.2.21

这是完整的 POM:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.brabantia.esb</groupId>
<artifactId>log-db</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>log-db</name>
<description>Log database application for TIBCO ESB</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<kotlin.version>1.2.21</kotlin.version>
<vaadin.version>8.3.0</vaadin.version>
<spring.boot.version>1.5.10.RELEASE</spring.boot.version>
<jupyter.version>5.1.0</jupyter.version>
<surefire.version>2.19.1</surefire.version>

<!-- Properties are prefixed with flyway. -->
<flyway.user>esb_logging_user</flyway.user>
<flyway.password>esb_logging_user</flyway.password>

<!-- List are defined as comma-separated values -->
<flyway.schemas>dbo</flyway.schemas>

<!-- Individual placeholders are prefixed by flyway.placeholders. -->
<!--<flyway.placeholders.keyABC>valueXYZ</flyway.placeholders.keyABC>-->
<!--<flyway.placeholders.otherplaceholder>value123</flyway.placeholders.otherplaceholder>-->
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-docs</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<!--<dependency>-->
<!--<groupId>com.h2database</groupId>-->
<!--<artifactId>h2</artifactId>-->
<!--<scope>runtime</scope>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>5.0.7</version>
</dependency>
<dependency>
<groupId>com.tibco</groupId>
<artifactId>jms</artifactId>
<version>8.4.1</version>
</dependency>
<dependency>
<groupId>com.tibco</groupId>
<artifactId>tibjms</artifactId>
<version>8.4.1</version>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${vaadin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<jvmTarget>1.8</jvmTarget>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<outputDirectory>${project.build.directory}/generated-sources/jaxb</outputDirectory>
<!-- The package of your generated sources -->
<packageName>com.brabantia.esb.logdb.schema</packageName>
<sources>
<source>src/main/resources/schemas/BrabantiaMain.xsd</source>
</sources>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>5.0.7</version>
<configuration>
<user>esb_logging_user</user>
<password>esb_logging_user</password>
<url>jdbc:sqlserver://localhost;database=esb_logging</url>
<schemas>
<schema>schema1</schema>
<schema>schema2</schema>
<schema>schema3</schema>
</schemas>
<placeholders>
<keyABC>valueXYZ</keyABC>
<otherplaceholder>value123</otherplaceholder>
</placeholders>
</configuration>
</plugin>
</plugins>
</build>


</project>

实体

日志实体

@Entity
@Table(name = "log")
internal data class LogEntity(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
val id: Long = -1,

@Column(name = "descriptive_message")
val descriptiveMessage: String = "",

@Column(name = "message_code")
val messageCode: String = "",

@OneToMany(mappedBy = "log", cascade = [(CascadeType.ALL)])
val references: MutableSet<LogReferenceEntity> = mutableSetOf(),

@OneToOne(mappedBy = "log", cascade = [(CascadeType.ALL)])
val messageContent: LogMessageContentEntity? = null
)

LogReference 实体

@Entity
@Table(name = "log_reference")
internal class LogReferenceEntity(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
val id: Long? = null,

@Column(name = "name")
val Name: String = "",

@Column(name = "value")
val value: String = "",

@ManyToOne
@JoinColumn(name = "log_id")
var log: LogEntity? = null)

LogMessageContent 实体

@Entity
@Table(name = "log_message_content")
internal data class LogMessageContentEntity(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
val id: Long? = null,

@Column(name = "message_content")
val messageContent: ByteArray = byteArrayOf(),

@Column(name = "create_date_time")
val createDateTime: LocalDateTime = LocalDateTime.now(),

@OneToOne(cascade = [(CascadeType.ALL)])
@JoinColumn(name = "log_id")
var log: LogEntity = LogEntity()
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false

other as LogMessageContentEntity

if (id != other.id) return false
if (!Arrays.equals(messageContent, other.messageContent)) return false
if (createDateTime != other.createDateTime) return false
if (log != other.log) return false

return true
}

override fun hashCode(): Int {
var result = id?.hashCode() ?: 0
result = 31 * result + Arrays.hashCode(messageContent)
result = 31 * result + createDateTime.hashCode()
result = 31 * result + log.hashCode()
return result
}
}

存储库

存储库都非常标准

@Transactional
internal interface LogRepository : CrudRepository<LogEntity, Long>

@Transactional
internal interface LogReferenceRepository : CrudRepository<LogReferenceEntity, Long>

@Transactional
internal interface LogMessageContentRepository : CrudRepository<LogMessageContentEntity, Long>

服务

我只有一项用于处理 Log 实例的服务,该服务还处理关联的 LogReferenceEntity 和 LogMessageContentEntity 对象。

@Service
@Transactional
internal class JpaLogService(
val logRepository: LogRepository,
val logReferenceRepository: LogReferenceRepository,
val logMessageContentRepository: LogMessageContentRepository) : LogService {

override fun retrieveLogs(): List<LogDTO> {
return logRepository.findAll().map { it.toDTO() }
}

override fun retrieveLog(id: Long): LogDTO? {
return logRepository.findOne(id)?.toDTO()
}

override fun addLog(logCreateDTO: LogCreateDTO): LogDTO {
val log = LogEntity.fromDto(logCreateDTO)

// Add a reference to each log instance, and persist to the database
log.references.forEach {reference ->
reference.log = log
logReferenceRepository.save(reference)
}

log.messageContent?.let {
it.log = log
logMessageContentRepository.save(it)
}

return logRepository.save(log).toDTO()
}
}

集成测试

我只添加了测试类的一部分。

发生的情况是,一旦运行将实例添加到数据库的测试,该实例在测试完成后就不会被删除。在此示例中,我省略了 @DirtiesContext 注释,我将在下面展示我尝试的内容。

@RunWith(SpringRunner::class)
@SpringBootTest
internal class JpaLogServiceTest {

@Autowired
lateinit var service: LogService

@Autowired
lateinit var repository: LogRepository

@Test
fun `'retrieveLogs' should retrieve empty list if repository doesn't contain entities`() {
assertThat(service.retrieveLogs()).isEmpty()
}

@Test
fun `'addLog' should return the created entity`() {
val result = service.addLog(logCreateDTO = LogCreateDTO())
assertThat(result).isNotNull()
assertThat(result.id).isNotNull()
}
}

@DirtiesContext 在没有任何参数的类上

@RunWith(SpringRunner::class)
@SpringBootTest
@DirtiesContext
internal class JpaLogServiceTest {
...
}

@DirtiesContext 在具有 classMode

的类上
@RunWith(SpringRunner::class)
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
internal class JpaLogServiceTest {
...
}

@DirtiesContext 将实例保存到数据库的测试方法

@RunWith(SpringRunner::class)
@SpringBootTest
internal class JpaLogServiceTest {

...

@Test
@DirtiesContext
fun `'addLog' should return the created entity`() {
val result = service.addLog(logCreateDTO = LogCreateDTO())
assertThat(result).isNotNull()
assertThat(result.id).isNotNull()
}
}

@DirtiesContext 位于使用 methodMode

将实例保存到数据库的测试方法上
@RunWith(SpringRunner::class)
@SpringBootTest
internal class JpaLogServiceTest {

...

@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
fun `'addLog' should return the created entity`() {
val result = service.addLog(logCreateDTO = LogCreateDTO())
assertThat(result).isNotNull()
assertThat(result.id).isNotNull()
}
}

我也尝试过一些其他的事情,但我感觉离我已经不远了。

有人可以插入我朝正确的方向前进吗?

最佳答案

您不需要使用@DirtiesContext来清除测试之间的数据库更改,尽管有时如果应用程序上下文在测试类之间共享不正确,则可能有必要。

相反;您应该将您的测试标记为@Transactional。这将确保每个测试方法都由 Spring 事务包装,无论结果如何都会回滚。

    @Test
@Transactional
fun `'addLog' should return the created entity`() {
val result = service.addLog(logCreateDTO = LogCreateDTO())
assertThat(result).isNotNull()
assertThat(result.id).isNotNull()
}

关于java - @DirtiesContext 不适用于 Spring Boot 和 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49273851/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com