了解測試裝具模塊 代碼是如何工作的?首先,指派 getalltests.py 獲取一組要執(zhí)行的 Test 類。然后,使用 Jython API 將這個列表從 Python 運(yùn)行時環(huán)境中提取出來。然后使用 Java Reflection API 構(gòu)建在表示 Test 類名的列表中的 String 對象的類實(shí)例。最后,用 JUnit API 將 Test 添加到 TestSuite 中。這四個庫的相互配合可以實(shí)現(xiàn)您的目標(biāo):動態(tài)構(gòu)建的 TestSuite 可以像靜態(tài)定義的那樣運(yùn)行。
/** * @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 ) );