我能够从Junit中模拟System.getenv值,但是当我执行测试用例时--在我的服务类中,System.getevn值以null形式出现。不知道我做错了什么。请查找我的测试服务类和junit类。
有些人能帮我解决这个问题吗?为什么我的实际服务类中没有设置这个值?
TestService.java
public class TestService {
public TestService() throws Exception {
loadTestMethod();
}
private void loadTestMethod() {
System.out.println("Environment vairlable : " + System.getenv("my_key_name"));
System.setProperty("app.key", System.getenv("my_key_name"));
}
}TestServiceTest.java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = { System.class })
@PowerMockIgnore("javax.management.*")
public class TestServiceTest {
@Mock
TestService testService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv("my_key_name")).thenReturn("Testing");
System.out.println("Junit Environment vairlable : " + System.getenv("my_key_name"));
testService = new TestService();
}
@Test
public void myServiceTest() {
}
}发布于 2018-03-25 18:42:49
仅仅因为PowerMockito允许我们模拟静态并不意味着我们应该。
您的类依赖于静态实现关注点,这使得单元测试在大多数情况下是很困难的。
考虑遵循Explicit Dependency Principle
方法和类应该明确要求(通常通过方法参数或构造函数参数)它们所需的任何协作对象,以便正确地工作。
创建所需功能的抽象
public interface SystemWrapper {
//The "standard" output stream
PrintStream out;
//Gets the value of the specified environment variable
string getenv(string name);
//Sets the system property indicated by the specified key.
string setProperty(String key, String value);
}实现将封装对静态系统类的实际调用。
public class SystemWrapperImplementation implements SystemWrapper {
//The "standard" output stream
public final PrintStream out = System.out;
//Gets the value of the specified environment variable
public string getenv(string name) {
return System.getenv(name);
}
//Sets the system property indicated by the specified key.
public string setProperty(String key, String value) {
return System.setProperty(key, value);
}
}然后,您的依赖类将需要重构以包含抽象。
public class TestService {
private SystemWrapper system;
public TestService(SystemWrapper system) throws Exception {
this.system = system;
string key = "app.key";
string name = "my_key_name";
loadTestMethod(key, name);
}
private void loadTestMethod(string key, string name) {
string environmentVariable = system.getenv(name);
system.out.println("Environment variable : " + environmentVariable);
system.setProperty(key, environmentVariable);
}
}现在,为了进行测试,您可以根据需要模拟所需的依赖关系,而不会产生任何不良影响。然后,在调用实际代码时,将在生产中使用该实现。
最后,我建议不要让构造函数抛出异常。构造函数主要用于变量的赋值。
https://stackoverflow.com/questions/49477530
复制相似问题