我有spring boot应用程序。我想为服务类中的方法编写一些单元测试。 我可以加载环境变量并在单元测试类中获取属性,但不能在服务类中做到这一点。从单元测试中获取的服务类环境始终为null。从应用程序到达它时,它将起作用。
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();
}
SomethingService.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;
}
}