我的应用程序中有 2 个DataSource
。
所以,为了获得所需的JdbcTemplate
,我使用@Qualifier
.但是,当我像下面一样时,测试运行...但如果在"测试方法"中使用了JdbcTemplate
,则会无限期地等待。
@Service
@Transactional
public class SampleDatabaseService {
@Autowired
@Qualifier("firstDbJdbcTemplate")
private JdbcTemplate firstDbJdbcTemplate;
@Autowired
@Qualifier("secondDbJdbcTemplate")
private JdbcTemplate secondDbJdbcTemplate;
@Cacheable("status")
public Map<String, Device> readAllValidDeviceStatus() {
Map<String, Device> allDeviceStatuses = new HashMap<>();
//Stops at below line indefinitely if "SpyBean" is used
List<StatusDetail> statusDetails = firstDbJdbcTemplate
.query(SqlQueries.READ_DEVICE_STATUS, BeanPropertyRowMapper.newInstance(StatusDetail.class));
statusDetails
.stream()
.filter(deviceStatus -> deviceStatus.getName() != "Some Invalid Name")
.forEach(deviceStatus -> allDeviceStatuses
.put(deviceStatus.getName(), buildDevice(deviceStatus)));
return allDeviceStatuses;
}
/** More Stuff **/
}
和测试:
@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 */
}
但是,当我在 Test
中用 @Autowired
替换@SpyBean
时,它工作正常。
为什么会这样?任何帮助将不胜感激。:)
以以下格式使用它
@MockBean(name = "firstDbJdbcTemplate")
private JdbcTemplate firstDbJdbcTemplate;
您可以简单地使用SpyBean
注释name
属性
@SpyBean(name = "firstDbJdbcTemplate")
private JdbcTemplate firstDbJdbcTemplate;