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模拟最终类:
这个解决方案看起来不错,因为我们不修改现有代码,但它为整个项目和所有最终类的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")
    
        ...
    }