Spring boot Springboot/Kotlin:测试注入另一个@ConfigurationProperties类的类的最佳实践
我在科特林有个项目 我创建了一个Spring boot Springboot/Kotlin:测试注入另一个@ConfigurationProperties类的类的最佳实践,spring-boot,unit-testing,kotlin,mockito,configurationproperties,Spring Boot,Unit Testing,Kotlin,Mockito,Configurationproperties,我在科特林有个项目 我创建了一个@ConfigurationProperties类,我想知道单元测试的最佳实践 以下是我的属性类: @ConstructorBinding @ConfigurationProperties(prefix = "myapp") data class MyAppProperties( /** * Base path to be used by myapp. Default is '/search'. */ val
@ConfigurationProperties
类,我想知道单元测试的最佳实践
以下是我的属性类:
@ConstructorBinding
@ConfigurationProperties(prefix = "myapp")
data class MyAppProperties(
/**
* Base path to be used by myapp. Default is '/search'.
*/
val basePath: String = "/myapp"
)
我在控制器中插入MyAppProperties:
@RestController
final class MyAppController(
myAppProperties: MyAppProperties
) {
...
}
@ExtendWith(MockitoExtension::class)
internal class MyAppControllerTest {
@Mock
lateinit var myAppProperties: MyAppProperties
@InjectMocks
lateinit var myAppController: MyAppController
...
}
我想测试我的控制器:
@RestController
final class MyAppController(
myAppProperties: MyAppProperties
) {
...
}
@ExtendWith(MockitoExtension::class)
internal class MyAppControllerTest {
@Mock
lateinit var myAppProperties: MyAppProperties
@InjectMocks
lateinit var myAppController: MyAppController
...
}
但我有以下错误:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class com.myapp.MyAppProperties
Mockito cannot mock/spy because :
- final class
解决此问题的最佳解决方案是什么:
- 允许Mockito模拟最终类:
- 使我的属性类
打开
- 通过Maven配置打开所有@ConfigurationProperties类:
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
<arg>-Xjvm-default=enable</arg>
</args>
<compilerPlugins>
<plugin>all-open</plugin>
</compilerPlugins>
<pluginOptions>
<option>all-open:annotation=org.springframework.boot.context.properties.ConfigurationProperties</option>
</pluginOptions>
</configuration>
...
</plugin>
@ExtendWith(MockitoExtension::class)
internal class MyAppControllerTest {
val myAppProperties: MyAppProperties = MyAppProperties("/mypath")
...
}