微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么我的 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 中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。