Android basics of automated testing --JUnit4, AndroidJunitRunner (support Andrews Junit), Espresso

table of Contents

Configuration

JUnit4

JUnit4 based approach notes

JUnit4 common assertion

Hamcrest and assertThat

Test method execution order

Espresso

Dependent libraries

Use JUnit4 test cases Rules created:

Use onView Find view

Performing an operation on view

Check the assertion meets a view

OnData AdapterView used in the controller (ListView, GridView, ...) in


Espresso (UI test - based Instrumentation and AndroidJunitRunner)

Configuration

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

JUnit4

JUnit folder in the project's location, after the project is created in the app - the src directory>

When you create a project, the default will generate a unit test example ExampleUnitTest.java

public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}

JUnit4 based approach notes

JUnit3 by class name and a test to determine whether the test method is the test, The test method must begin test. In JUnit4 in, it is determined by the comments.

  • @Test
    shows that the method is a test method. Test methods must be public void, you may throw an exception.
  • @Before
    it will be called once before each test method is executed.
  • @After
    and @Before correspondence, it will be executed after each test method are called once.
  • @BeforeClass
    it will be called once before any test method is executed. The difference is that with @Before: @Before annotated method will be called before the execution time of each method, the number of test methods will fall by the number of times; and the method @BeforeClass annotated only once, all of the test method called once before execution. Note that the annotated test method must be public static void modified.
  • @AfterClass
    and @BeforeClass correspondence, it will be called once after all the testing method execution is completed. Note that the annotated test method must be public static void modified.
  • @Ignore
    ignore this test method, sometimes when we do not want to run a test method, you can add the comment.
public class TestJUnitLifeCycle {

    @BeforeClass
    public static void init() {
        System.out.println("------init()------");
    }

    @Before
    public void setUp() {
        System.out.println("------setUp()------");
    }

    @After
    public void tearDown() {
        System.out.println("------tearDown()------");
    }

    @AfterClass
    public static void finish() {
        System.out.println("------finish()------");
    }

    @Test
    public void test1() {
        System.out.println("------test1()------");
    }

    @Test
    public void test2() {
        System.out.println("------test2()------");
    }
}

JUnit4 common assertion

JUnit provides some auxiliary functions, they used to help us determine whether the method was tested normally performed as expected, we call these helper functions assertion (Assertion). JUnit4 all assertions are org.junit.Assert class, Assert class contains a set of static test methods used to verify that the logical expectations of the relationship between the expected and the actual value of the actual is correct, if not in line with our expectations, said test fails.

  • assertEquals ([message], expected, actual)
    to verify the desired value and actual values are equal, then the test passed if they are equal, not equal, then the test fails represented, with an exception AssertionError. message indicates that the custom error message, is optional, the following are identical.
  • assertNotEquals ([message], unexpected, actual)
    to verify the desired value and the actual values are not equal.
  • assertArrayEquals ([message], expecteds, actuals)
    verify that the two arrays are the same
  • assertSame ([message], expected, actual)
    asserts two references point to the same object.
  • assertNotSame ([message], expected, actual)
    asserts two references to different objects.
  • assertNull ([message], object)
    assert that an object is null.
  • assertNotNull ([message], object)
    asserts that the object is not null.
  • assertTrue ([message], condition)
    predicate condition is true.
  • assertFalse ([message], condition)
    asserted that the condition is false.

Hamcrest and assertThat

JUnit4 Hamcrest combination provides a new assertion syntax: assertThat, combined with matching character Hamcrest provided, can express all of the test ideas, the problems mentioned above are also solved.
When using gradle introduced JUnit4.12 already contains hamcrest-core.jar, hamcrest-library.jar, hamcrest-integration.jar three jar package, so we do not need extra then import hamcrest related libraries alone.
assertThat defined as follows:

public static <T> void assertThat(String reason, T actual,
            Matcher<? super T> matcher)

Related string matcher

startsWith
endsWith
containsString
equalToIgnoringCase
equalToIgnoringWhiteSpace

Correlation value matcher

closeTo
greaterThan
lessThan
lessThanOrEqualTo
greaterThanOrEqualTo

A collection of related matcher

hasEntry
hasKey
hasValue
hasItem
hasItems
hasItemInArray

Objects related matcher

notNullValue
nullValue
sameInstance
instanceOf
hasProperty

Combination logic matcher

allOf
anyOf
both
either
is
isA
not
any
anything

Use as follows:

assertThat("android studio", startsWith("and"));
assertThat("android studio", endsWith("dio"));
assertThat("android studio", containsString("android"));
assertThat("android studio", equalToIgnoringCase("ANDROID studio"));
assertThat("android studio ", equalToIgnoringWhiteSpace(" android studio "));

Test method execution order

JUnit4 configured to provide annotation @ FixMethodOrder execution sequence, optionally values ​​are: MethodSorters.NAME_ASCENDING, MethodSorters.DEFAULT, MethodSorters.JVM

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestExecOrder {

    @Test
    public void testD() {
        System.out.println("DDDDD");
    }

    @Test
    public void testA() {
        System.out.println("AAAAA");
    }

    @Test
    public void testB() {
        System.out.println("BBBBB");
    }

    @Test
    public void testC() {
        System.out.println("CCCCC");
    }
    
}

 

Espresso

Espresso is Google strongly recommended a testing framework, version from Android studio2.2 start, google has supported espresso automatically generate unit test code on as, work together based on Instrumentation and AndroidJunitRunner

Dependent libraries

  • espresso-core comprising a base view matcher, and the assertion repository operation
  • espresso-web test libraries included webview
  • espresso-idling-resource contains mechanisms to synchronize and back-office jobs
  • espresso-contrib comprises DatePicker, RecyclerView and Drawer actions, accessibility checks, and CountingIdlingResource these extensions
  • espresso-intent with the intention of including the Test Library
  • espresso-remote Espresso multiple function processing position

Use JUnit4 test cases Rules created:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class HelloWorldEspressoTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class);

    @Test
    public void listGoesOverTheFold() {
        onView(withText("Hello world!")).check(matches(isDisplayed()));
    }
}

 

Use onView Find view

onView(allOf(withId(R.id.my_view), withText("Hello!")))

Performing an operation on view

onView(…).perform(click());

onView(…).perform(click());

onView(…).perform(scrollTo(), click());

Check the assertion meets a view

 

onView(…).check(matches(withText("Hello!")));

The  AdapterView controller ( ListViewGridViewuse, onData is, ...) in

AdapterView Control is a special adapter to load data from dynamic. The most common  AdapterView Shi ListView. And like  LinearLayout static control such contrary, in view of the current structure, it is possible to load only a AdapterView part of the child controls, the simple  onview() search can not find are not currently loaded view. Espresso By providing separate  onData() entry point for addressing this problem, it can have an entry before the entry of the problem or child to load (it gets focus) operation adapter

1. Click an entry to open the selection box Spinner

onView(withId(R.id.spinner_simple)).perform(click());

2. Click on the entry

For entry to choose from, Spinner with its content creates a  ListView. list element does not appear in the view structure. By using  onData() our compulsory element you will want to get added to the view structure. Spinner elements in the string, we want to match the entry is a string type and the value is "Jack".

onData(allOf(is(instanceOf(String.class)), is("Jack"))).perform(click());

3. Verify  TextView comprising "Americano" string

onView(withId(R.id.spinnertext_simple).check(matches(withText(containsString("Jack"))));

 

发布了58 篇原创文章 · 获赞 4 · 访问量 4万+

Guess you like

Origin blog.csdn.net/jackron2014/article/details/104054721