java - 如何在单元测试调用的服务类方法中读取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;
}
}
解决方案
推荐阅读
- javascript - componentWIllMount() using window.location.hash value, But how i provide this value while testing in jest
- c# - Is it possible to capture that "Send/Receive" event programmatically using VSTO?
- python - 如何在 Python 中提取两个字符串之间的内容?
- java - Maven build on Eclipse: java.lang.OutOfMemoryError: Java heap space
- react-native - React Native Scrollview scroll back to first image
- r - Warning in Sys.setlocale in R
- spring - What is difference between application context and spring context?
- c# - 比较未知对象类型时如何确保对字符串进行不区分大小写的比较?
- c++ - 将字节数组转换为有字节序问题的指针
- javascript - 列选择 - AgGrid 社区