Getting Started with Testing -- start unit test, startedtesting

Source: Internet
Author: User

Getting Started with Testing -- start unit test, startedtesting

Android tests are based on JUnit, and you can run them either as local unit tests on the JVM or as instrumented tests on an Android device. this page provides an introduction to the concepts and tools for building Android tests.

// Android testing is based on JUnit

Test Types

When using Android Studio to write any of your tests, your test code must go into one of two different code directories (source sets ). for each module in your project, Android Studio includes both source sets, corresponding to the following test types:

// For each project module, Androidstudio will contain these two types of source sets

Local unit tests
Located module-name/src/test/java/.

These tests run on the local JVM and do not have access to functional Android framework APIs.

// These tests run on the local Java Virtual Machine and do not access the APIS at the Android framework layer.

To get started, see Building Local Unit Tests.

Instrumented tests
Located module-name/src/androidTest/java/.

These are all tests that must run on an Android hardware device or an Android emulator.

// These tests must run on Android hardware devices or simulators.

Instrumented tests are built into an APK that runs on the device alongside your app under test. the system runs your test APK and your app under tests in the same process, so your tests can invoke methods and modify fields in the app, and automate user interaction with your app.

// Instruments test has built an apk and installed it with your app. The system will run your app and the test apk in the same process, in this way, your test can call methods in the application and modify variables to automate interaction with the application.

For information about how to create instrumented tests, see the following topics:

  • Building Instrumented Unit Tests: Build complex unit tests with Android dependencies that cannot be satisfied with mock objects.
  • Automating User Interface Tests: Create tests to verify that the user interface behaves correctly for user interactions within a single app or for interactions wait SS multiple apps.
  • Testing App Component Integrations: Verify the behavior of components that users do not directly interact with, such as a Service or aContent Provider.

However,Local unit testsAndInstrumented testsDescribed abve are just terms that help distinguish the tests that run on your local JVM from the tests that run on the Android platform (on a hardware device or emulator ). the real testing types that you shoshould understand when building a complete test suite are described in the following table.

// However, the local unit test and instrumentes test described above only helps distinguish between local virtual machines and Android platforms. The classification of true test types should be described in the following table:

Type Subtype Description
Unit tests
Local Unit Tests Unit tests that run locally on the Java Virtual Machine (JVM). Use these tests to minimize execution time when your tests have no Android framework dependencies or when you can mock the Android framework dependencies.
Instrumented unit tests Unit tests that run on an Android device or emulator. These tests have accessInstrumentationInformation, such asContextOf the app you are testing. Use these tests when your tests have Android dependencies that mock objects cannot satisfy.
Integration Tests
Components within your app only This type of test verifies that the target app behaves as expected when a user performs a specific action or enters a specific input in its activities. for example, it allows you to check that the target app returns the correct UI output in response to user interactions in the app's activities. UI testing frameworks like Espressoallow you to programmatically simulate user actions and test complex intra-app user interactions.
Cross-app Components This type of test verifies the correct behavior of interactions between different user apps or between user apps and system apps. for example, you might want to test that your app behaves correctly when the user performs an action in the Android Settings menu. UI testing frameworks that support cross-app interactions, such as UI Automator, allow you to create tests for such scenarios.
Test APIs

The following are common APIs used for testing apps on Android.

JUnit

You shoshould write your unit or integration test class as a JUnit 4 test class. The framework offers a convenient way to perform common setup, teardown, and assertion operations in your test.

A basic JUnit 4 test class is a Java class that contains one or more test methods. A test method begins with@TestAnnotation and contains the code to exercise and verify a single functionality (that is, a logical unit) in the component that you want to test.

The following snippet shows an example JUnit 4 integration test that uses the Espresso APIs to perform a click action on a UI element, then checks to see if an expected string is displayed.

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

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

    @Test
    public void sayHello(){
        onView(withText("Say hello!")).perform(click());

        onView(withId(R.id.textView)).check(matches(withText("Hello, World!")));
    }
}

In your JUnit 4 test class, you can call out sections in your test code for special processing by using the following annotations:

// You can use the annotations below to evoke special processing for some code segments.

  • @Before: Use this annotation to specify a block of code that contains test setup operations. The test class invokes this code block before each test. You can have multiple@BeforeMethods but the order in which the test class callthese methods is not guaranteed. // use the before annotation to specify the code block containing the test code build operation. The test class calls this code block before all the test code, you can have multiple code blocks declared by before, but their relative running sequence cannot be guaranteed.
  • @After: This annotation specifies a block of code that contains test tear-down operations. The test class callthis code block after every test method. You can define multiple@AfterOperations in your test code. Use this annotation to release any resources from memory // after annotation specifies the code block containing the removal work of the test class. The test class calls this code after all the test methods, you can define multiple after annotation code blocks. Use this annotation to release memory resources
  • @Test: Use this annotation to mark a test method. A single test class can contain multiple test methods, each prefixed with this annotation. // use the test annotation to mark the test method. A test class can contain multiple test methods. Each method has the test prefix.
  • @Rule: Rules allow you to flexibly add or redefine the behavior of each test method in a reusable way. in Android testing, use this annotation together with one of the test rule classes that the Android Testing Support Library provides, suchActivityTestRuleOrServiceTestRule. // Rule allows you to flexibly add and rush to define the behavior of each test method for reuse. In the Android test, it is used together with other test rule classes, for exampleActivityTestRuleOrServiceTestRule.
  • @BeforeClass: Use this annotation to specify static methods for each test class to invoke only once. this testing step is useful for expensive operations such as connecting to a database. // use this annotation to specify a static method that will only be called once for each test class. This test setup method is very helpful for overhead operations such as database connection.
  • @AfterClass: Use this annotation to specify static methods for the test class to invoke only after all tests in the class have run. This testing step is useful for releasing any resources allocated in@BeforeClassBlock.
  • @Test(timeout=): Some annotations support the ability to pass in elements for which you can set values. for example, you can specify a timeout period for the test. if the test starts but does not complete within the given timeout period, it automatically fails. you must specify the timeout period in milliseconds, for example:@Test(timeout=5000). // Some annotations support adding elements with configurable values. For example, you can specify a supermarket time for this test. If the test starts but is not completed within the time-out period, it will automatically fail. The time-out period is specified in milliseconds.

For more annotations, see the documentation for JUnit annotations and the Android annotations.

Use the JUnitAssertClass to verify the correctness of an object's state. the assert methods compare values you have CT from a test to the actual results and throw an exception if the comparison fails. assertion classes describes these methods in more detail.

Android Testing Support Library

The Android Testing Support Library provides a set of APIs that allow you to quickly build and run test code for your apps, including JUnit 4 and functional UI tests. the library provided des the following instrumentation-based APIs that are useful when you want to automate your tests:

AndroidJUnitRunnerA JUnit 4-compatible test runner for Android. espressoA UI testing framework; suitable for functional UI testing within an app. UI AutomatorA UI testing framework suitable for cross-app functional UI testing between both system and installed apps. assertion classes

Because Android Testing Support Library APIs extend JUnit, you can use assertion methods to display the results of tests. an assertion method compares an actual value returned by a test to an expected value, and throws an AssertionException if the comparison test fails. using assertions is more convenient than logging, and provides better test performance.

To simplify test development, you shocould use the Hamcrest library, which lets you create more flexible tests using the Hamcrest matcher APIs.

Monkey and monkeyrunner

The Android SDK implements des two tools for functional-level app testing:

Monkey
This is a command-line tool that sends pseudo-random streams of keystrokes, touches, and gestures to a device. you run it with the Android Debug Bridge (adb) tool, and use it to stress-test your app, report back errors any that are encountered, or repeat a stream of events by running the tool multiple times with the same random number seed.
Monkeyrunner
This tool is an API and execution environment for test programs written in Python. the API provided des functions for connecting to a device, installing and uninstalling packages, taking screenshots, comparing two images, and running a test package against an app. using the API, you can write a wide range of large, powerful, and complex tests. you run programs that use the API with monkeyrunnerCommand-line tool.
Guides for Building Android Tests

The following components provide more detail about how to build and run a variety of test types:

Building Local Unit Tests
Build unit tests that have no dependencies or only simple dependencies that you can mock, which run on your local JVM.
Building Instrumented Unit Tests
Build complex unit tests with Android dependencies that cannot be satisfied with mock objects, which run on a hardware device or emulator.
Automatic User Interface Tests
Create tests to verify that the user interface behaves correctly for user interactions within a single app or for interactions messaging SS multiple apps.
Testing App Compontent Integrations
Verify the behavior of components that users do not directly interact with, such as a service or a content provider.
Testing Display Performance
Write tests that measure your app's UI performance to ensure a consistently smooth user experience.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.