[关闭]
@mSolo 2015-06-01T03:33:02.000000Z 字数 9539 阅读 2374

Android 测试学习笔记(一)

Android 测试 TDD 持续集成


测试内容

  1. Activity and Fragment lifecycle events
  2. Database and FileSystem operations
  3. Network capabilities
  4. Screen densities and Screen sizes
  5. Availability of sensors
  6. Keyboard and other input devices
  7. GPS
  8. External storage

测试类别


Instrumentation : android.test.InstrumentationTestRunner(default runner)
  1. testApplicationId "com.blundell.something.non.default"
  2. testInstrumentationRunner "com.blundell.tut.CustomTestRunner"
  3. testHandleProfiling false
  4. testFunctionalTest true
  5. testCoverageEnabled true

测试教程(Part One)

第一个测试

  1. public class MainActivityTest extends TestCase {
  2. public MainActivityTest() {
  3. super("MainActivityTest");
  4. }
  5. public MainActivityTest(String name) { //
  6. super(name);
  7. }
  8. @SmallTest
  9. public void testSomething() throws Exception {
  10. fail("Not implemented yet");
  11. }
  12. }
  1. 从命令行执行测试
    am instrument [flags] <COMPONENT> -r -e <NAME> <VALUE> -p <FILE> -w

    1. adb shell
    2. am instrument -w -e class
    3. com.blundell.tut.MainActivityTest\#testSomething
    4. com.blundell.tut.test/android.test.InstrumentationTestRunner
    • 获取测试用例清单
      am instrument -e log true
    • <NAME> <VALUE> 其它取值有:package、coverage
  2. Test Annotations

    • @SmallTest、@MediumTest、@LargeTest
    • @Smoke(android.test.suitebuilder.SmokeTestSuiteBuilder)
    • @FlakyTest(@FlakyTest(tolerance=4))
    • @UIThreadTest
    • @Suppress
  3. 创建自定义 annotation

  1. @Retention(RetentionPolicy.RUNTIME)
  2. public @Interface VeryImportantTest {
  3. }
  4. // ...
  5. @VeryImportantTest
  6. public void testOtherStuff() {
  7. fail("Also not implemented yet");
  8. }
  1. am instrument -w -e annotation com.blundell.tut.VeryImportantTest
  2. com.blundell.tut.test/android.test.InstrumentTestRunner

View Assertions

  1. public void testUserInterfaceLayout() {
  2. int margin = 0;
  3. View origin = mActivity.getWindow().getDecorView();
  4. assertOnScreen(origin, editText);
  5. assertOnScreen(origin, button);
  6. assertRightAligned(editText, button, margin);
  7. }

MoreAsserts

  1. @UiThreadTest
  2. public void testNoErrorInCapitalization() {
  3. String msg = "capitalize this text";
  4. editText.setText(msg);
  5. button.performClick();
  6. String actual = editText.getText().toString();
  7. String notExpectedRegexp = "(?i:ERROR)";
  8. String errorMsg = "Capitalization error for " + actual;
  9. assertNotContainsRegex(errorMsg, notExpectedRegexp, actual);
  10. }

TouchUtils class

  1. public void testListScrolling() {
  2. listView.scrollTo(0, 0);
  3. TouchUtils.dragQuarterScreenUp(this, activity);
  4. int actualItemPosition = listView.getFirstVisiblePosition();
  5. assertTrue("Wrong position", actualItemPosition > 0);
  6. }

Mock objects【but stubs, suggests extend】

The IsolatedContext Class

文件与数据库操作的测试

基本测试基类

其它基本测试类或方法

The assertActivityRequiresPermission() method

public void assertActivityRequiresPermission(String packageName, String className, String permission)

  1. public void testActivityPermission() {
  2. String pkg = "com.blundell.tut";
  3. String activity = PKG + ".MyContactsActivity";
  4. String permission = android.Manifest.permission.CALL_PHONE;
  5. assertActivityRequiresPermission(pkg, activity, permission);
  6. }

The assertReadingContentUriRequiresPermission() method

public void assertReadingContentUriRequiresPermission(Uri uri, String permission)

The assertWritingContentUriRequiresPermission() method

public void assertWritingContentUriRequiresPermission(Uri uri, String permission)

The ActivityMonitor inner class

  1. public void testFollowLink() {
  2. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_VIEW);
  3. intentFilter.addDataScheme("http");
  4. intentFilter.addCategory(Intent.CATEGORY_BROWSABLE);
  5. Instrumentation inst = getInstrumentation();
  6. ActivityMonitor monitor = inst.addMonitor(intentFilter, null, false);
  7. TouchUtils.clickView(this, linkTextView);
  8. monitor.waitForActivityWithTimeout(3000);
  9. int monitorHits = monitor.getHits();
  10. inst.removeMonitor(monitor);
  11. assertEquals(1, monitorHits);
  12. }

The InstrumentationTestCase class

The launchActivity() and launchActivityWithIntent() methods

public fina T launchActivity(String pkg, Class<T> activityCls, Bundle extras)
public final T launchActivityWithIntent(String pkg, Class<T> activityCls, Intent intent)

The sendKeys() and sendRepeatedKeys() methods

  1. public void testSendKeyInts() {
  2. requestMessageInputFocus();
  3. sendKeys(
  4. KeyEvent.KEYCODE_H,
  5. KeyEvent.KEYCODE_E,
  6. KeyEvent.KEYCODE_E,
  7. KeyEvent.KEYCODE_E,
  8. KeyEvent.KEYCODE_Y,
  9. KeyEvent.KEYCODE_DPAD_DOWN,
  10. KeyEvent.KEYCODE_ENTER);
  11. /*
  12. sendRepeatedKeys(
  13. 1, KeyEvent.KEYCODE_H,
  14. 3, KeyEvent.KEYCODE_E,
  15. 1, KeyEvent.KEYCODE_Y,
  16. 1, KeyEvent.KEYCODE_DPAD_DOWN,
  17. 1, KeyEvent.KEYCODE_ENTER);
  18. */
  19. // sendKeys("H 3*E Y DPAD_DOWN ENTER");
  20. String actual = messageInput.getText().toString();
  21. assertEquals("HEEEY", actual);
  22. }
  23. private void requestMessageInputFocus() {
  24. try {
  25. runTestOnUiThread(new Runnable() {
  26. @Override
  27. public void run() {
  28. messageInput.requestFocus();
  29. }
  30. });
  31. } catch (Throwable throwable) {
  32. fail("Could not request focus.");
  33. }
  34. instrumentation.waitForIdleSync();
  35. }

The scrubClass() method

protected void scrubClass(class<?> testCaseClass)
- invoked from the tearDown() method
- clean up class virables for prevent memory leaks for large test suites.

The ActivityInstrumentationTestCase2 class

The setUp() and tearDown() method

  1. protected void setUp() throws Exception {
  2. super.setUp();
  3. // this must be called before getActivity()
  4. // disabling touch mode allows for sending key events
  5. setActivityInitialTouchMode(false);
  6. activity = getActivity();
  7. instrumentation = getInstrumentation();
  8. linkTextView = (TextView)activity.findViewById(R.id.main_text_link);
  9. messageInput = (EditText)activity.findViewById(R.id.main_input_message);
  10. capitalizeButton = (Button)activity.findViewById(R.id.main_button_capitalize);
  11. }
  12. protected void tearDown() throws Exception {
  13. super.tearDown();
  14. myObject.dispose();
  15. }

ProviderTestCase2 examples

  1. public void testQuery() {
  2. String segment = "dummySegment";
  3. Uri uri = Uri.withAppendedPath(MyProvider.CONTENT_URI, segment);
  4. Cursor c = provider.query(uri, null, null, null, null);
  5. try {
  6. int actual = c.getCount();
  7. assertEquals(2, actual);
  8. } finally {
  9. c.close();
  10. }
  11. }
  12. public void testDeleteByIdDeletesCorrectNumberOfRows() {
  13. String segment = "dummySegment";
  14. Uri uri = Uri.withAppendedPath(MyProvider.CONTENT_URI, segment);
  15. int actual = provider.delete(uri, "_id = ?", new String[]{"1"});
  16. assertEquals(1, actual);
  17. }

The ServiceTestCase

The TestSuiteBuilder.FailedToCreateTests class

The TestSuiteBuilder.FailedToCreateTests class is a special TestCase class used to indicate a failure during the build() step.

在测试中使用库

  1. import com.blundell.dummylibrary.Dummy;
  2. public class MyFirstProjectActivity extends Activity {
  3. private Dummy dummy;
  4. @Override
  5. public void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. final EditText messageInput = (EditText) findViewById(R.id.main_input_message);
  9. Button capitalizeButton = (Button) findViewById(R.id.main_button_capitalize);
  10. capitalizeButton.setOnClickListener(new OnClickListener() {
  11. @Override
  12. public void onClick(View v) {
  13. String input = messageInput.getText().toString();
  14. messageInput.setText(input.toUpperCase());
  15. }
  16. });
  17. dummy = new Dummy();
  18. }
  19. public Dummy getDummy() {
  20. return dummy;
  21. }
  22. public static void methodThatShouldThrowException() throws Exception {
  23. throw new Exception("This is an exception");
  24. }
  25. }
  1. public void testDummy() {
  2. assertNotNull(activity.getDummy());
  3. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注