我为我的应用程序创建了多个测试用例,所有这些都链接在一个测试套件类中。
但是,我想将第一个测试中创建的对象传递给其他人。
更清楚地说,第一个测试测试一个类,该类使用来 self 的数据库的数据创建一个复杂的对象。我希望其他人测试对象本身的方法。
这是我定义测试套件类的方式:
package tests.testSuites;
import tests.Test1;
import tests.Test2;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
Test1.class
Test2.class
})
public class DataTestSuite {
}
但我想在某个地方有这样的东西:
MyObject obj=Test1.testcreation();
Test2.testMethod(obj);
如何将常规 JUnit testSuite 类定义与将创建的对象传递给其他测试的需要结合起来?
编辑
有关信息,测试套件在测试运行程序类中启动。此类有助于格式化结果并创建自定义日志文件。
这就是它调用测试套件的方式:
public class MetExploreTestRunner {
public static void main(String[] args) {
Result result=JUnitCore.runClasses(DataTestSuite.class);
if(result.wasSuccessful()){
System.out.println("All tests succesful ");
}else{
for(Failure failure:result.getFailures()){
System.out.println(failure.toString());
}
}
}
}
最佳答案
不要这样做。每个测试应该独立于其他测试。然后,您可以单独运行测试来调试它们,并且每个测试都更容易理解。此外,JUnit 以任意顺序运行测试;您不能保证该对象将在使用之前被创建。
如果多个测试使用类似的对象,请考虑将创建它的代码提取到测试类的共享私有(private)方法中。如果许多测试使用该对象,请考虑将其设置为由 @before 方法设置的测试装置。
关于java - JUnit 4 : Test case returns an object used in other tests in the test suite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26753514/