我想避免在集成测试中连接到 Ldap,所以我添加了
LDAPConnectionPool
的模拟,所以我有一个像这样的测试类:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
internal class MyControllerTest{
...
@TestConfiguration
internal class LdapConnectionPoolConfig {
@Bean
@Primary
fun ldapConnectionPool(): LDAPConnectionPool {
return mockk()
}
}
@Test
fun foo() {...}
当我在调试中开始测试时,我看到调用了内部类的方法,但也调用了生产配置,因此出现错误:
The bean 'ldapConnectionPool', defined in ****.MyControllerTest$LdapConnectionPoolConfig, could not be registered. A bean with that name has already been defined in class path resource [****/LdapConnectionPoolConfig.class] and overriding is disabled.
我尝试通过以下方式启用覆盖:
spring:
main:
allow-bean-definition-overriding: true
但在这种情况下,我看到另一个错误(无法加载生产配置,尽管我希望它根本不会加载):
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ldapConnectionPoolConfig' defined in file [****\LdapConnectionPoolConfig.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name '****.LdapConnectionProperties': Could not bind properties to 'LdapConnectionProperties' : prefix=ldap.connection, ignoreInvalidFields=false, ignoreUnknownFields=true
附注
如果我使用顶级类进行具有相同包和名称的配置 - 一切正常:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Import(LdapConnectionPoolConfig::class)
class MyControllerTest {
和
@TestConfiguration
class LdapConnectionPoolConfig {
@Bean
fun ldapConnectionPool(): LDAPConnectionPool = mockk()
如果我将配置名称更改为
LdapConnectionPoolConfigAnotherName
,一切都会停止工作,并且我会看到前面提到的相同错误
但我更喜欢内部类的方法
在您的测试类中,您可以声明用
@MockBean
注释的所需类型的字段:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
internal class MyControllerTest{
@MockBean
private var ldapConnectionPool: LDAPConnectionPool
}