【发布时间】:2021-03-04 00:20:59
【问题描述】:
为什么 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 不为我连接这些值?
【问题讨论】:
标签: spring-boot junit4 spring-boot-test