TestCases for test Activities and Account Sync Provides Context, and Instrumentation AndroidTestCase TestCases for test Providers, Services, Loaders and Applications Provides Context, and permissions asserts
but launched one time for all tests methods in the TestCase. (ActivityUnitTestCase and ActivityInstrumentationTestCase launch activity each time setUp() is called)
MockContext, and a MockContentResolver. Data is not saved at the same place as usual! It can also be used from other TestCases newResolverWithContentProviderFromSql(Context targetContext, String filenamePrefix, Cla
MockContext MockCursor MockDialogInterface MockPackageManager MockResources However, most of them are not really useful: they are only classes ske leton, that throw UnsupportedOperationException... ...Excepted MockContentResolver
plug yourself your providers! addProvider(String name, ContentProvider provider) notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) In case of ContentProviderTestCase2, only one provider is plugged.
ContextWrapper to mock Contexts A contextWrapper is a Context, that delegate all method execution t o another Context. Subclass it for... Mock Context!
Intents we tried to send. And it provides also a MockAccountManager! Prevent tests from talking to the device: checkUriPermission() return permission Granted getFilesDir() return File("/dev/null") getSystemService() return null getAndClearBroadcastIntents()
Presence of a view in screen Location of a view in screen Alignement ViewGroup contains view or not assertGroupContains(ViewGroup parent, View child) assertLeftAligned(View first, View second) assertHasScreenCoordinates(View origin, View view, int x, int y) assertOnScreen(View origin, View view)
@LargeTest, @Smoke One for suppress a test @Suppress One for define tolerance @FlakyTest(tolerance = 2) And one that force test to execute on UI Thread @UiThreadTest
ProviderTestCase2<CarProvider>{ public CarProviderTest() { super(CarProvider.class, "com.roly.carseller.carprovider"); } public void testInsert() { //Given CarProvider provider = getProvider(); Car car = new Car("BMW"); provider.insert(car); //When Car fromDB = provider.query(car.getId()); //Then assertEquals(car.getBrand(),fromDB.getBrand()); } } ¡This is not real code!
android In a subclass of InstrumentationTestRunner public class CoolAppInstumentation extends InstrumentationTestRunner{ @Override public TestSuite getAllTests() { TestSuite testSuite = new TestSuite(); testSuite.addTest(new TestSuiteBuilder(CoolAppInstrumentation.class) .includePackages("com.roly.mycoolapp.test.sync") .build()); return testSuite; } }
on Test size? You have to define "predicates". Predicate<TestMethod> smallTests = new Predicate<TestMethod>(){ @Override public boolean apply(TestMethod testMethod) { return testMethod.getAnnotation(SmallTest.class) != null; } } new TestSuiteBuilder(MyInstrumentation.class).include(...) .addRequirements(smallTests) .build(); ...
void testAndroidTestCaseSetupProperly() ... class MyServiceTest extends ServiceTestCase { @Override @Suppress public void testServiceTestCaseSetUpProperly() ... Keep only what you care about
are great objects to convey Mocks In all AndroidTestCases: public void testMeImFamous(){ setContext(myMockContext); ... } In ContentProvider constructor: public ContentProvider(Context context, String readPermission, String writePermission, And everywhere you pass a Context.
tests Use RenamingDelegatingContext, and IsolatedContext mContextWrapper = new RenamingDelegatingContext(getContext(), "test-"); mContext = new IsolatedContext(mResolver, mContextWrapper); It will prevent you from: Erase file Modify database Add crap account on your phone
you don't want to run async code! You can force you test to wait if you get any callback or event Use Java's CountDownLatch for that. final CountDownLatch latch = new CountDownLatch(1); final BroadcastReceiver syncReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { latch.countDown(); } } try { latch.await(60, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(); }
It can facilitate your life! //Get private field Field privateField = myObject.getClass.getDeclaredField("mParser"); //Set it accessible privateField.setAccessible(true); //Inject a value privateField.set(myObject, new Parser()); //Then invoke a method parseMethod.invoke(myObject, "stuff to parse");
(imho) BUT Don't do it yourself Suggestions RandomStringUtils (Apache commons lang) Random (Java.utils) DataFactory Great library that generate random consistent data Example: getName() can return "Peter"
don't exist. There are (crap) solutions to get around this Use constructor Use static block boolean set to true when first setUp Count visited tests Note that the class TestSetup from jUnit3 is not part of the framework
base framework Facilitate a lot manipulation of UI public void testDisplayBlackBox() { //Enter 10 in first edit-field solo.enterText(0,"10"); //Enter 20 in second edit-field solo.enterText(1,"20"); //Click on Multiply button solo.clickOnButton("Multiply"); //Verify that resultant of 10 x 20 assertTrue(solo.searchText("200")); }
jvm It uses jUnit4! No need to deploy on device = So much time saved! @RunWith(HttpTest.RobolectricTestRunner.class) public class HttpTest { @Before public void setup() { Robolectric.setDefaultHttpResponse(200, "OK"); } @Test public void testGet_shouldApplyCorrectHeaders(){ HashMap<String, String> headers=new HashMap<String, String>(); headers.put("foo", "bar"); http.get("www.example.com", headers, null, null); HttpRequest sent = Robolectric.getSentHttpRequest(0); assertThat(sent.getHeaders("foo")[0].getValue(), equalTo("bar")); } }
assertEquals(View.GONE, view.getVisibility()); Ὃ assertThat(view).isGone(); assertThat(layout).isVisible() .isVertical() .hasChildCount(4) .hasShowDividers(SHOW_DIVIDERS_MIDDLE); And it's also extensible, you can had your own assertions
instance of your class verify(myMock).someMethod() verify that a method has been called when(myMock.getUser()).thenReturn(new User()) specify what to return when a m Context context = Mockito.mock(Context.class); Mockito.when(context.getContentResolver()) .thenReturn(Mockito.mock(ContentResolver.class)); //Do something Mockito.verify(context).getContentResolver();
android emulator plugin. It provides all you need to automate tests. Additionnally, if you want to get the state 'unstable', you need to add a property with maven. mvn android:instrument -Dmaven.test.failure.ignore=true ...