我有一个如下所示的单元测试类,
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MyTest {
private static final int MY_CONSTANT = 7;
private String expectedValue = "expected value";
@Test
public void test1() {
int value = 50; // get by processing
int ans = value / MY_CONSTANT ;
String actual = "actual string"; // get by processing
Assert.assertEquals(expectedValue, actual);
}
@Test
public void test2() {
int value = 40; // get by processing
int ans = value / MY_CONSTANT ;
String actual = "actual string 2"; // get by processing
Assert.assertEquals(expectedValue, actual);
}
}
人们会像下面这样写,
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MyTest {
@Test
public void test1() {
int value = 50; // get by processing
int ans = value / 7 ;
String actual = "actual string"; // get by processing
Assert.assertEquals("expected value", actual);
}
@Test
public void test2() {
int value = 40; // get by processing
int ans = value / 7 ;
String actual = "actual string 2"; // get by processing
Assert.assertEquals("expected value", actual);
}
}
两者都可以正常工作,但是在这样的单元测试方法之间共享成员变量是一个好的做法吗?
以上两种方法中最好的方法是什么?
最佳答案
当然,如果共享值是不可变的。无论语言/测试框架如何,在测试之间共享可变值通常不是一个好主意。这可能会限制您以特定顺序运行测试,或者要求您在运行依赖测试之前运行某些会改变值的测试。
另一个考虑因素是,在测试之间共享常量值可能会使它们在代码更改时变得更脆弱或更难维护。它介绍了测试之间可能不必要的耦合。
问自己一个很好的问题是我正在做出什么权衡?如果它只是为断言定义一个常量,那么我可能不会这样做,除非该值对我来说是负担。在每个测试中定义。
关于java - 在单元测试之间共享成员变量是一个好习惯吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48706008/