uiautomator 启动原理
首先启动的时候指定运行的类和方法
-c majcit.com.UIAutomatorDemo.SettingsSample#test001
开始提取你指定的类和方法
public void addTestClasses(List<String> classNames) throws ClassNotFoundException { for (String className : classNames) { addTestClass(className); } }
如果有#号探测到,会调用addTestClass(String className, String methodName),把method加入测试类
public void addTestClass(String className) throws ClassNotFoundException { int hashPos = className.indexOf('#'); String methodName = null; if (hashPos != -1) { methodName = className.substring(hashPos + 1); className = className.substring(0, hashPos); } addTestClass(className, methodName); }
public void addTestClass(String className, String methodName) throws ClassNotFoundException { Class<?> clazz = this.mClassLoader.loadClass(className); if (methodName != null) { addSingleTestMethod(clazz, methodName); } else { Method[] methods = clazz.getMethods(); for (Method method : methods) { if (this.mFilter.accept(method)) { addSingleTestMethod(clazz, method.getName()); } } } }
看addSingleTestMethod是如何根据测试类clazz和它的一个方法创建一个junit.framework.TestCase对象的,
这些TestCase保存在TestCaseCollector对象的mTestCases这个列表里面。
这里千万要注意的一点是;并非一个测试脚本(类)一个TestCase,而是一个方法创建一个TestCase!
protected void addSingleTestMethod(Class<?> clazz, String method) { if (!this.mFilter.accept(clazz)) { throw new RuntimeException("Test class must be derived from UiAutomatorTestCase"); } try { TestCase testCase = (TestCase)clazz.newInstance(); testCase.setName(method); this.mTestCases.add(testCase); } catch (InstantiationException e) { this.mTestCases.add(error(clazz, "InstantiationException: could not instantiate test class. Class: " + clazz.getName())); } catch (IllegalAccessException e) { this.mTestCases.add(error(clazz, "IllegalAccessException: could not instantiate test class. Class: " + clazz.getName())); } }
Junit运行
protected void start() { ... for (TestCase testCase : testCases) { prepareTestCase(testCase); testCase.run(testRunResult); } ... }
protected void runTest() throws Throwable { assertNotNull(fName); // Some VMs crash when calling getMethod(null,null); Method runMethod= null; try { // use getMethod to get all public inherited // methods. getDeclaredMethods returns all // methods of this class but excludes the // inherited ones. runMethod= getClass().getMethod(fName, (Class[])null); } catch (NoSuchMethodException e) { fail("Method \""+fName+"\" not found"); } if (!Modifier.isPublic(runMethod.getModifiers())) { fail("Method \""+fName+"\" should be public"); } try { runMethod.invoke(this, (Object[])new Class[0]); } catch (InvocationTargetException e) { e.fillInStackTrace(); throw e.getTargetException(); } catch (IllegalAccessException e) { e.fillInStackTrace(); throw e; } }