为什么我的 Spring Boot 单元测试不会在服务类中加载 @Value 属性?

问题描述

为什么 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 中。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...