07/09/2018, 15:29

Chuyển từ AndroidTestCase sang AndroidJUnit4

Trước đây: public class SomeClassTest extends AndroidTestCase { private SomeClass klass; @Override protected void setUp() throws Exception { super.setUp(); // This old way that we all get used to. final Context context = getContext(); final SharedPreferences preferences = ...

Trước đây:

public class SomeClassTest extends AndroidTestCase {
  private SomeClass klass;

  @Override protected void setUp() throws Exception {
    super.setUp();

    // This old way that we all get used to.
    final Context context = getContext();
    final SharedPreferences preferences = context.getSharedPreferences(
        SomeClassTest.class.getSimpleName(),
        Context.MODE_PRIVATE
    );
    klass = new SomeClass(context, preferences);
  }

  public void testShouldBeTrue() {
    // I hate that prefix 'test' though!
  }
}

Bây giờ:

@RunWith(AndroidJUnit4.class)
public class SomeClassTest {
  private SomeClass klass;

  @Before public void setUp() {
    // InstrumentationRegistry will do the trick!
    // We can use this context to test implementations of SQLiteOpenHelper.
    final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();

    // It's also easy to create mock SharedPreferences for testing.
    final SharedPreferences preferences = context.getSharedPreferences(
        SomeClassTest.class.getSimpleName(),
        Context.MODE_PRIVATE
    );
    klass = new SomeClass(context, preferences);
  }

  @Test public void shouldBeTrue() {
    // Do something with klass and assert it here.
  }
}
0