【发布时间】:2016-07-30 13:40:59
【问题描述】:
示例代码:
public class Count {
static int count;
public static int add() {
return ++count;
}
}
我希望 test1 和 test2 完全分开运行,以便它们都通过。我怎样才能完成呢?我的 IDE 是 Intellij IDEA。
public class CountTest {
@Test
public void test1() throws Exception {
Count.add();
assertEquals(1, Count.count);//pass.Now count=1
}
@Test
public void test2() throws Exception {
Count.add();
assertEquals(1, Count.count);//error, now the count=2
}
}
假设 test1 在 test2 之前运行。
这只是一个简化的代码。实际上代码更复杂,所以我不能只在@after 方法中创建count=0。
【问题讨论】:
-
但是这样做的目标是什么?基本上你正在测试静态方法,所以堆上没有特定对象的实例。我的建议是重构您的代码以不使用 static 方法。其他解决方案是使用
@Before注释并在那里重置所有需要的值。
标签: java unit-testing intellij-idea junit