Spring Boot 单元测试注入properties文件的属性(好文章,申精!)

项目中想自定义一个properties文件存放支付相关的属性,并在单元测试中获取这个属性进行测试。

发现注入不成功,对此进行研究。

分析过程:

如下图所示在resources目录下创建一个pay.properties文件:

并在其中其中存放需要的key和value

然后开始编写单元测试类:


 
 
  1. package com.pingxx.example;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.core.io.ClassPathResource;
  11. import org.springframework.test.context.ContextConfiguration;
  12. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  13. @RunWith(SpringJUnit4ClassRunner.class)
  14. public class PayTest {
  15. static final Logger logger = LoggerFactory.getLogger(PayTest.class);
  16. @Value( "${pay.apiKey}")
  17. private String apiKey;
  18. @Value( "${pay.appId}")
  19. private String appId;
  20. @Value( "${pay.privateKeyPath}")
  21. private String privateKeyPath;
  22. @Test
  23. public void valueTest(){
  24. // Assert.assertNotNull(apiKey);
  25. logger.debug(apiKey);
  26. }
  27. }

发现日志系统打印出来的apiKey对应的值为:"${pay.apiKey}",显然不对。

估计是此时还没有加载配置文件,因此把pay.properties内的内容复制到application.properties试试,发现还不行。

 

搜了一下(http://www.baeldung.com/properties-with-spring)得到如下内容:

 

因此对代码进行修改:


 
 
  1. package com.pingxx.example;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.context.annotation.PropertySource;
  10. import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
  11. import org.springframework.test.context.ContextConfiguration;
  12. import org.springframework.test.context.TestPropertySource;
  13. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  14. @RunWith(SpringJUnit4ClassRunner.class)
  15. public class PayTest {
  16. static final Logger logger = LoggerFactory.getLogger(PayTest.class);
  17. @Value( "${pay.apiKey}")
  18. private String apiKey;
  19. @Value( "${pay.appId}")
  20. private String appId;
  21. @Value( "${pay.privateKeyPath}")
  22. private String privateKeyPath;
  23. @Test
  24. public void valueTest(){
  25. // Assert.assertNotNull(apiKey);
  26. logger.debug(apiKey);
  27. }
  28. @Configuration
  29. @PropertySource( "classpath:pay.properties")
  30. static class PropertiesWithJavaConfig {
  31. @Bean
  32. public static PropertySourcesPlaceholderConfigurer
  33. propertySourcesPlaceholderConfigurer () {
  34. return new PropertySourcesPlaceholderConfigurer();
  35. }
  36. }
  37. }

发现apiKe的值被正确输出。大功告成!

等等,作为追求完美的年轻人我们不能就此满足,继续查查官方文档,是否有更好的解决方案呢?

打开spring boot的官方参考手册(“spring-boot-reference”,点击可以下载)看看,能否有更好方法呢?

我们通过搜索“PropertySource”发现了如下内容:

啥?TestPropertySource,看这名字就应该是和测试相关的属性注解,看看后面的解释"annotations on your tests",果然!

我们删除上面的代码只新增一个注解看看


 
 
  1. package com.pingxx.example;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.test.context.ContextConfiguration;
  8. import org.springframework.test.context.TestPropertySource;
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @TestPropertySource( "classpath:pay.properties")
  12. public class PayTest {
  13. static final Logger logger = LoggerFactory.getLogger(PayTest.class);
  14. @Value( "${pay.apiKey}")
  15. private String apiKey;
  16. @Value( "${pay.appId}")
  17. private String appId;
  18. @Value( "${pay.privateKeyPath}")
  19. private String privateKeyPath;
  20. @Test
  21. public void valueTest(){
  22. // Assert.assertNotNull(apiKey);
  23. logger.debug(apiKey);
  24. }
  25. }

发现果真输出了我们需要的value.

建议:

最近发现官方的参考手册和GitHub代码和示例是最权威和最全面的参考文档。

建议不管学习什么技术,都要下载下来,没事的适合读读,遇到问题的适合多查查。

如果觉得本文对你有帮助,欢迎点赞,欢迎关注我,如果有补充欢迎评论交流,我将努力创作更多更好的文章。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了许多方便的工具来编写和运行单元测试。您可以使用JUnit或者Spring Boot自带的测试框架来编写单元测试。 首先,您需要在项目的pom.xml文件中添加测试相关的依赖。通常情况下,Spring Boot已经默认为您添加了JUnitSpring Boot Test依赖,您只需要确保它们存在即可。 接下来,您可以创建一个测试类,并在类上添加`@RunWith(SpringRunner.class)`注解。这将告诉JUnit使用Spring Runner运行测试。您还可以使用`@SpringBootTest`注解来指定要加载的Spring Boot应用程序的配置。 然后,您可以在测试方法上使用`@Test`注解来标记要运行的测试方法。在测试方法中,您可以使用各种断言方法来验证预期的结果。 例如,假设您有一个名为`UserService`的服务类,其中包含一个名为`getUserById`的方法,用于根据用户ID获取用户信息。您可以编写以下单元测试: ```java @RunWith(SpringRunner.class) @SpringBootTest public class UserServiceTest { @Autowired private UserService userService; @Test public void testGetUserById() { User user = userService.getUserById(1L); assertNotNull(user); assertEquals("John Doe", user.getName()); assertEquals("john@example.com", user.getEmail()); } } ``` 在这个例子中,我们使用了`@Autowired`注解将`UserService`注入测试类中。然后,我们编写了一个名为`testGetUserById`的测试方法,使用断言方法来验证`getUserById`方法的返回结果是否符合预期。 运行测试时,Spring Boot会自动启动整个应用程序上下文,并注入所需的依赖项。您可以使用各种断言方法来验证预期的结果。 这只是Spring Boot单元测试的一个简单示例,您可以根据实际需求编写更复杂的测试。希望对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值