首页 > 解决方案 > 如何在单元测试调用的服务类方法中读取spring boot属性文件

问题描述

我有弹簧启动应用程序。我想为服务类中的方法编写一些单元测试。我可以在单元测试类中加载环境变量并获取属性,但不能在服务类中执行。从单元测试中访问服务类中的环境时,它始终为空。从应用程序到达它时它会起作用。

SomethingServiceTest.java

@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(value = "/application.properties")
public class SomethingServiceTest {

     private ISomethingService m_SomethingService;

     @PostConstruct
     public void setup() {
        m_SomethingService = new SomethingService();
        m_SomethingService.setSomethingRepository(somethingRepository);
        // somethingRepository is mocked class, probably not important
     }

    @Test
    public void test_somethingMethod() {
         System.out.println(env.getProperty("some.property"));
         //env here is full and i get wanted property
         m_uploadService.doSomething();
    }

ISomethingService.java

public interface ISomethingService {
    doSomething();
}

东西服务.java

@Service
public class SomethingService implements ISomethingService {

    @Value("${some.property}")
    private String someProperty;

    private ISomethingRepository somethingRepository;

    @Autowired
    public ISomethingRepository getSomethingRepository() {
        return somethingRepository;
    }

    public void setSomethingRepository(ISomethingRepository p_somethingRepository) {
        somethingRepository = p_somethingRepository;
    }

    @Autowired
    private Environment env;

    @Override
    @Transactional
    public String doSomething(){
        System.out.println(env.getProperty("some.property"));
        //env is null here
        return someProperty;
    }
}

标签: javaspring-boot

解决方案


推荐阅读