Android Test Driven Development

后端 未结 6 1831
轻奢々
轻奢々 2021-01-29 22:32

I have considerable experience in making Android applications. For my new project, we have decided to do Test Driven Development (TDD). I have been getting my hands wet on Robot

6条回答
  •  一整个雨季
    2021-01-29 23:13

    • I use ActivityInstrumentationTestCase2 in the case of Activities for TDD (or BDD rather), and write normal unit tests for all logic. This also helps me separate logic from Activities.
    • Mobile applications by nature are UI centric. Therefore it does not make sense to mock out the UI, even if it makes the Unit test look like a Functional Test.
    • For adding Extras to intents, you can set a custom intent for the test, or do it for all tests by overriding setup.
    • Mocks give a lot of issues on Android, so I use stubs.

    An example is given below. The Activity shows Hello World when you click a button -

    public class HelloWorldActivityTest extends
            ActivityInstrumentationTestCase2 {
    
        private HelloWorld activity;
    
        public HelloWorldActivityTest() {
            super(HelloWorldActivityTest.class);
        }
    
        public void testShouldRenderGreetingOnButtonClick() {
            activity = this.getActivity();
            Button button = (Button) activity.findViewById(R.id.btn_greet);
            TouchUtils.clickView(this, button);
            assertEquals("Hello World!",
                    ((TextView) activity.findViewById(android.R.id.greeting_text))
                            .getText());
        }
    
    }
    

    EDIT: Things have changed since I posted the answer. Mockito now has reasonably good support for Android. And for tests, we've moved from ActivityInstrumentationTestCase2 to Robolectric, just in order to tap the sheer speed of JVM in the development phase. The Android Testing Framework is great for Integration and Functional testing, just not for Unit Tests.

提交回复
热议问题