我有一个在初始化期间分配了静态变量的类。我想为这个类编写单元测试,修改这个静态变量的值。下面是一个简单的代码来解释我的场景
要测试的课程:
public class Hello {
private final static String HELLO_FINAL = "Hello " + HelloTo.getInstance().getHelloTo(); // I would like to modify this value between tests
public String sayHello() {
return HELLO_FINAL;
}
}
支持班:
public class HelloTo {
private String helloTo = "World";
private static HelloTo singleton = new HelloTo();
private HelloTo() {}
public static HelloTo getInstance() {
return singleton;
}
public void setHelloTo(String helloTo) {
this.helloTo = helloTo;
}
public String getHelloTo() {
return helloTo;
}
}
测试类:
import org.junit.Assert;
import org.junit.Test;
public class HelloTest {
@Test
public void testDefault() {
Assert.assertEquals("Hello World", new Hello().sayHello());
}
@Test
public void testDynamic() {
HelloTo.getInstance().setHelloTo("My name");
Assert.assertEquals("Hello My name", new Hello().sayHello());
}
}
有没有办法让两个测试都成功。目前我对testDymanic()说:
失败了org.junit.ComparisonFailure: expected:<Hello [World]> but was:<Hello [My name]>
提前致谢!
答案 0 :(得分:2)
在测试中使用可变单例是一个已知问题。您必须在测试之间重置单例的状态,更好的是,不要在测试中使用单例。
您可以执行以下操作:
public enum HelloTo {
INSTANCE;
private String helloTo = "World";
public void reset() {
setHelloTo("World");
}
public void setHelloTo(String helloTo) {
this.helloTo = helloTo;
}
public String getHelloTo() {
return helloTo;
}
}
public class Hello {
public static String sayHello() {
// has to be dynamic as helloTo can change.
return "Hello " + HelloTo.INSTANCE.getHelloTo();
}
}
public class HelloTest {
@Before
public void setUp() {
HelloTo.INSTANCE.reset();
}
@Test
public void testDefault() {
Assert.assertEquals("Hello World", Hello.sayHello());
}
@Test
public void testDynamic() {
HelloTo.INSTANCE.setHelloTo("My name");
Assert.assertEquals("Hello My name", Hello.sayHello());
}
}
答案 1 :(得分:0)
HELLO_FINAL
每次运行仅初始化一次;您无法在同一JVM中重新初始化它。有没有办法让两个测试成功?当然,有无数的方法。但这取决于您尝试测试的内容,这在您的示例中并不完全清楚。