了解测试装具模块 代码是如何工作的?首先,指派 getalltests.py 获取一组要执行的 Test 类。然后,使用 Jython API 将这个列表从 Python 运行时环境中提取出来。然后使用 Java Reflection API 构建在表示 Test 类名的列表中的 String 对象的类实例。最后,用 JUnit API 将 Test 添加到 TestSuite 中。这四个库的相互配合可以实现您的目标:动态构建的 TestSuite 可以像静态定义的那样运行。
/** * @return TestSuite A test suite containing all our tests (as found by Python script) */ private TestSuite getTestSuite() { TestSuite suite = new TestSuite();
// get Iterator to class names we're going to add to our Suite Iterator testClassNames = getClassNamesViaJython().iterator();
/** * Get list of tests we're going to add to our suite * @return List A List of String objects, each representing class name of a TestCase */ private List getClassNamesViaJython() { // run python script interpreter.execfile( getPathToScript() );
// extract out Python object named PYTHON_OBJECT_NAME PyObject allTestsaspythonObject = interpreter.get( PYTHON_OBJECT_NAME );
// convert the Python object to a String[] String[] allTests = (String[]) allTestsAsPythonObject.__tojava__( String[].class );
// add all elements of array to a List List testList = new ArrayList(); testList.addAll( Arrays.asList( allTests ) );