【发布时间】:2020-04-11 06:22:32
【问题描述】:
我有一个抽象服务类,它自动装配指定类型的存储库。
abstract class SomeService<T extends SomeRepository<U>, U ...> {
@Autowrired
@Accessors(fluent = true)
@Getter(PROTECTED)
private U repositoryInstance;
}
现在我正在尝试为服务类的子类创建一个抽象测试类。
@SpringBootTest
abstract class SomeServiceTest<T extends SomeService<U>, U extends SomeRepository<V>, V ...> {
@Autowrired
@Accessors(fluent = true)
@Getter(PROTECTED)
private T serviceInstance;
// DOES NOT WORK!
@MockBean
@Accessors(fluent = true)
@Getter(PROTECTED)
private U repositoryInstance; // != serviceInstance.repositoryInstance();
}
但是在实际服务类的测试类中模拟 bean 是可行的。
class OtherServiceTest
extends SomeServiceTest<OtherService, OtherRepository, ...> {
@TestConfiguration
OtherServiceTestConfiguration {
// WORKS!!!
// == serviceInstance().repositoryInstance();
@MockBean private OtherRepository repositoryInstance;
}
}
class AnotherServiceTest
extends SomeServiceTest<AnotherService, AnotherRepository, ...> {
// WORKS!!!
// == serviceInstance().repositoryInstance();
@MockBean private AnotherRepository repositoryInstance;
}
如何模拟 SomeServiceTest#repositoryInstance 以便它引用与 SomeServiceTest#serviceInstance.repositoryInstance() 相同的对象?
【问题讨论】:
标签: java spring spring-boot mockito spring-boot-test