Spring boot 使用@SpyBean和@Qualifier Spring引导测试
我的应用程序中有2个Spring boot 使用@SpyBean和@Qualifier Spring引导测试,spring-boot,mockito,spring-test,Spring Boot,Mockito,Spring Test,我的应用程序中有2个DataSources 因此,为了获得所需的jdbc模板,我使用@限定符。但是,当我喜欢下面,测试运行。。。但如果在“测试中的方法”中使用了JdbcTemplate,则会无限期地等待 @服务 @交易的 公共类SampleDatabaseService{ @自动连线 @限定符(“firstDbJdbcTemplate”) 私有JdbcTemplate firstDbJdbcTemplate; @自动连线 @限定符(“secondDbJdbcTemplate”) 私有JdbcTe
DataSource
s
因此,为了获得所需的jdbc模板
,我使用@限定符
。但是,当我喜欢下面,测试运行。。。但如果在“测试中的方法”中使用了JdbcTemplate
,则会无限期地等待
@服务
@交易的
公共类SampleDatabaseService{
@自动连线
@限定符(“firstDbJdbcTemplate”)
私有JdbcTemplate firstDbJdbcTemplate;
@自动连线
@限定符(“secondDbJdbcTemplate”)
私有JdbcTemplate secondDbJdbcTemplate;
@可缓存(“状态”)
公共地图readAllValidDeviceStatus(){
Map allDeviceStatuses=new HashMap();
//如果使用“SpyBean”,则会无限期地停在下面一行
List statusDetails=firstDbJdbcTemplate
.query(sqlquerys.READ_DEVICE_STATUS,beanpropertyrowapper.newInstance(StatusDetail.class));
状态详细信息
.stream()
.filter(deviceStatus->deviceStatus.getName()!=“一些无效名称”)
.forEach(设备状态->所有设备状态
.put(deviceStatus.getName(),buildDeviceStatus(deviceStatus));
返回所有设备状态;
}
/**更多的东西**/
}
以及测试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Transactional
@Rollback
@ActiveProfiles("test")
public class SampleDatabaseServiceTest {
@SpyBean
@Qualifier("firstDbJdbcTemplate")
private JdbcTemplate firstDbJdbcTemplate;
@Autowired
private SampleDatabaseService serviceUnderTest;
@Before
public void populateTables() {
//Insert some Dummy Records in "InMemory HSQL DB" using firstDbJdbcTemplate
}
@Test
public void testReadAllValidDeviceStatus() {
// When
Map<String, Device> allDeviceStatuses = serviceUnderTest.readAllValidDeviceStatus();
// Then
assertThat(allDeviceStatuses).isNotNull().isNotEmpty();
// More checks
}
/* More Tests */
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=SpringBootTest.webEnvironment.RANDOM\u端口)
@交易的
@回滚
@ActiveProfiles(“测试”)
公共类SampleDatabaseServiceTest{
@间谍
@限定符(“firstDbJdbcTemplate”)
私有JdbcTemplate firstDbJdbcTemplate;
@自动连线
私有SampleDatabaseService服务测试中;
@以前
公共void populateTables(){
//使用firstDbJdbcTemplate在“InMemory HSQL DB”中插入一些虚拟记录
}
@试验
公共无效测试ReadAllValidDeviceStatus(){
//什么时候
Map AllDeviceStatus=serviceUnderTest.readAllValidDeviceStatus();
//然后
assertThat(AllDeviceStatus).isNotNull().isNotEmpty();
//更多支票
}
/*更多测试*/
}
但是,当我在Test
中将@SpyBean
替换为@Autowired
时,它工作正常
为什么会这样?非常感谢您的帮助。:) 以下面的格式使用它
@MockBean(name = "firstDbJdbcTemplate")
private JdbcTemplate firstDbJdbcTemplate;
@MockBean(name = "firstDbJdbcTemplate")
private JdbcTemplate firstDbJdbcTemplate;