问题描述
为什么 Spring Boot 不会测试加载服务类中的 @Value
属性?我有一个带有此属性的服务类。
@Value("${azure.storage.connection-string}")
private String connectionString;
我正在使用 JUnit4
。当此测试运行时,connectionString
属性为空。
@TestPropertySource(locations="classpath:/application-test.yml")
@Slf4j
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
public class BlobServiceTest {
@Autowired
private ObjectMapper objectMapper;
private BlobService blobServiceSpy;
@Before
public void setup() {
blobServiceSpy = Mockito.spy(new BlobService(objectMapper));
}
@Test
public void testGetExampleBlob() {
String stubFileId = UUID.randomUUID().toString();
PdfBlob pdfBlob = null;
try {
pdfBlob = blobServiceSpy.downloadBlobContent(stubFileId);
} catch (JsonProcessingException e) {
log.error("Test failed.",e);
Assert.fail();
}
Assert.assertNotNull("PDF blob was null.",pdfBlob);
}
}
在this question中有某种答案,但很不清楚,答案需要更多信息。
这行得通,但看起来像是“黑客”:
public class BlobServiceTest {
@Value("${azure.storage.containerName}")
private String containerName;
@Value("${azure.storage.connection-string}")
private String connectionString;
@Autowired
private ObjectMapper objectMapper;
private BlobService blobServiceSpy;
@Before
public void setup() {
blobServiceSpy = Mockito.spy(new BlobService(objectMapper));
//TODO not sure why,but had to setup connectionString property this way
blobServiceSpy.containerName = this.containerName;
blobServiceSpy.connectionString = this.connectionString;
}
当我创建 Spy 对象时,为什么 SpringBootTest 不为我连接这些值?
解决方法
当您使用 new 创建您的 BlobService
时,spring 并不知道它,因此不会注入您的属性。尝试@Autowire
您的 blob 服务,然后将其封装在 spy 中。