我有 3 个测试类,如下:
包 com.junittest.testcases;
测试3类:
import junit.framework.TestCase;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import annotations.DataSetRule;
import annotations.DataSets;
import com.junittest.test.MyClass;
public class Test3 extends TestCase{
MyClass m = new MyClass();
String group = "user";
@Rule
public TestRule dataSetRule = new DataSetRule();
@Test
public void test5() {
System.out.println("In Test 5");
//assertEquals(5, m.add(2,3));
}
@Test
public void test6() throws Exception {
org.junit.Assume.assumeTrue(group.equals("user"));
System.out.println("In Test 6");
//assertEquals(-2, m.sub(2,3));
}
@DataSets({"dataset","dataset1"})
@Test
public void test7() {
System.out.println("In Test 7");
}
@Ignore
@Test
public void test8() {
System.out.println("in test8");
}
}
测试2类:
package com.junittest.testcases;
import org.junit.Test;
import singletons.SingletonClass;
import com.junittest.test.MyClass;
import junit.framework.TestCase;
public class Test2 extends TestCase{
MyClass m = new MyClass();
public void setUp() {
SingletonClass sc = SingletonClass.getInstance();
System.out.println(SingletonClass.callCount);
}
@Test
public void test3() {
assertEquals(5, m.add(2,3));
}
@Test
public void test4() {
assertEquals(-2, m.sub(2,3));
}
}
测试1类:
package com.junittest.testcases;
import org.junit.Test;
import singletons.SingletonClass;
import com.junittest.test.MyClass;
import junit.framework.TestCase;
public class Test1 extends TestCase{
MyClass m = new MyClass();
public void setUp() {
SingletonClass sc = SingletonClass.getInstance();
System.out.println(SingletonClass.callCount);
}
@Test
public void test1() {
assertEquals(4, m.add(2,3));
}
@Test
public void test2() {
assertEquals(-1, m.sub(2,3));
}
}
还有一个 TestSuite 类:
package com.junittest.testcases;
import rules.SomeTest;
import singletons.SingletonClass;
import junit.framework.Test;
import junit.framework.TestSuite;
public class TestSuite1 {
public static Test suite() {
SingletonClass sc = SingletonClass.getInstance();
System.out.println(SingletonClass.callCount);
TestSuite suite = new TestSuite(TestSuite.class.getName());
suite.addTestSuite(Test1.class);
suite.addTestSuite(Test2.class);
suite.addTestSuite(Test3.class);
return suite;
}
}
问题是,在 Eclipse 中运行 JUnit 中的 TestSuite1 类时,它忽略了 Test3 类中的 @Rule 标记,因此输出不符合预期。为什么它忽略@Rule标签。有没有其他方法可以执行这三种情况?
最佳答案
您正在混合 JUnit 3 (junit.framework.*
) 和 JUnit 4 (org.junit.*
) 代码。如果您仅使用 JUnit 4,该问题应该会消失。
- 删除
extends TestCase
(它们很简单,不需要,因为您的测试是用@Test
注释的。 - 将
@Before
注释添加到您的setUp()
方法中。 - 使用 JUnit4 套件:https://github.com/junit-team/junit/wiki/Aggregating-tests-in-suites
关于java - 在 JUnit 中使用 TestSuite 时 @Rule 注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20879258/