Unit Testing in Android

Step by Step

Created by Wig Cheng (鄭元誠) and Chang Yu-heng (張昱珩)

2014-07-07

Creative Commons License Creative Commons License Creative Commons License

Software Development Process

The V-Model

v-model

Coding  Unit Test

=> Test-driven development (TDD)

Unit Testing

An unit can be viewed as the smallest testable part of an application

  • An entire interface or an individual method in object-oriented programming
  • An entire module or an individual function/procedure in procedural programming

Production Code

Test Code

public int sum(int x, int y) {
  return x + y;
}

public void testSum() {
  int i = sum(1, 2);
  assertEquals(i, 3);
}

Testing Methods

  • White-box testing
  • The testing code is dedicated for the implementation

    Pros:

    • Good coverage and implementation checking

    Cons:

    • High cost
  • Black-box testing
  • The testing code is dedicated for the interface

    Pros:

    • Good for interface checking
  • Grey-box testing

Basic Code Coverage Criteria

  • Function coverage
  • Statement coverage
  • Branch coverage
  • Condition coverage

Branch Coverage

Production Code

Test Code

public int max(int x, int y) {
  if (x > y)
    return x;
  else
    return y;
}

public void testMax() {
  int i = max(2, 1);
  assertEquals(i, 2);
  i = max(6, 9);
  assertEquals(i, 99);
}

Building an Unit Testing Environment

Software Requirement

  • JDK
  • Android SDK
  • Android Studio (IDE)
  • Genymotion (emulator)

Writing Test Cases

Testing Tools

  • Robolectric
  • Wouldn’t it be nice to run your Android tests directly from inside your IDE?

  • uiautomator
  • Automated functional UI test cases

  • MonkeyTalk
  • Capture and replay the test cases

  • CTS

Q & A