【发布时间】:2011-03-02 14:36:58
【问题描述】:
我在使用测试套件运行的一些 JUnit 4 测试时遇到问题。
如果我单独运行测试,它们可以正常运行,但在大多数测试方法中运行时,90% 的测试方法会因错误而失败。我注意到的是,第一个测试总是很好,但其余的都失败了。另一件事是,一些测试方法没有按正确的顺序执行(反射没有按预期工作,或者因为方法的检索不一定按照创建的顺序)。如果有多个测试具有相同名称的方法,通常会发生这种情况。我尝试调试一些测试,似乎从一行到下一行,某些属性的值变成了null。
有谁知道问题出在哪里,或者行为是否“正常”?
提前致谢。
附:
好的,测试不相互依赖,它们都没有,它们都有@BeforeClass、@Before、@After、@AfterClass,所以在测试之间一切都被清除了。测试与数据库一起工作,但在 @BeforeClass 中的每个测试之前都会清除数据库,所以这应该不是问题。
简单示例:
测试套件:
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
importy testclasses...;
@RunWith(Suite.class)
@Suite.SuiteClasses({ Test1.class, Test2.class })
public class TestSuiteX {
@BeforeClass
public static void setupSuite() { System.out.println("Tests started"); }
@AfterClass
public static void setupSuite() { System.out.println("Tests started"); }
}
测试: 测试是在 Glassfish 上运行的服务器应用程序上进行功能测试。
现在测试扩展了一个基类,该基类具有@BeforeClass - 清除数据库和登录名的方法以及仅进行注销的@AfterClass。 这不是问题的根源,因为在引入此类之前发生了同样的事情。
该类具有一些在其他测试中未使用的公共静态属性,并实现了 2 个控制方法。
其余的类,在本例中,这两个类扩展了基类,并且不覆盖继承的控制方法。
测试类示例:
imports....
public class Test1 extends AbstractTestClass {
protected static Log log = LogFactory.getLog( Test1.class.getName() );
@Test
public void test1_A() throws CustomException1, CustomException2 {
System.out.println("text");
creates some entities with the server api.
deletes a couple of entities with the server api.
//tests if the extities exists in the database
Assert.assertNull( serverapi.isEntity(..) );
}
}
第二个:
public class Test1 extends AbstractTestClass {
protected static Log log = LogFactory.getLog( Test1.class.getName() );
private static String keyEntity;
private static EntityDO entity;
@Test
public void test1_B() throws CustomException1, CustomException2 {
System.out.println("text");
creates some entities with the server api, adds one entities key to the static attribute and one entity DO to the static attribute for the use in the next method.
deletes a couple of entities with the server api.
//tests if the extities exists in the database
Assert.assertNull( serverapi.isEntity(..) );
}
@Test
public void test2_B() throws CustomException1, CustomException2 {
System.out.println("text");
deletes the 2 entities, the one retrieved by the key and the one associated with the static DO attribute
//tests if the deelted entities exists in the database
Assert.assertNull( serverapi.isEntity(..) );
}
这是一个基本示例,实际测试更复杂,但我尝试了简化测试,但仍然无法正常工作。 谢谢。
【问题讨论】:
-
您能否发布一个测试示例并说明您是如何运行测试套件的。
-
该测试套件是一个 JUnit 4 测试套件,它设置了所有测试类,并有一个 @BeforeClass 和一个 @AfterClass,它们仅 SOP 一些次要信息(基本字符串)。
-
您发布的代码遗漏了最重要的细节:1)AbstractTestClass,2)@BeforeClass、@Before、@After、@AfterClass 方法,3)如何以及何时初始化 keyEntity 和实体, 4) 哪个测试失败了,究竟是怎么失败的?
标签: java junit4 test-suite