Android Test (iv): Local unit Test

Source: Internet
Author: User

Android Test (iv): Local unit Test

Release date December 20, 2017 bug Master

Original: https://developer.android.com/training/testing/unit-testing/local-unit-tests.html

If your unit tests are not dependent or have only a simple Android dependency, you should run the tests on your local development machine. This test method is very efficient because it helps you avoid the overhead of loading the target application and unit test code into the real machine or emulator each time you run the test. As a result, the execution time of running unit tests is greatly reduced. In this way, you typically use a mock framework (such as Mockito) to accomplish any dependency.

Setting up a test environment

In your Android studio project, you must store the source files for your local unit tests in the module-name/src/test/java/directory. When you create a new project, the directory already exists.

You also need to configure the project's test dependencies to use the standard APIs provided by the JUnit 4 framework. If your tests need to interact with Android dependencies, include the Mockito library to simplify local unit testing. To learn more about using mock objects in your local unit tests, see simulating Android dependencies.

In your app's directory, locate the Build.gradle file, and specify the libraries as dependencies:

// Required -- JUnit 4 framework    testCompile ‘junit:junit:4.12‘    // Optional -- Mockito framework    testCompile ‘org.mockito:mockito-core:1.10.19‘}
To create a local unit test class

Your local unit test class should be written as a JUnit 4 test class. JUnit is the most popular and widely used unit testing framework in Java. The latest version of this framework, JUnit 4, allows you to write tests in a much clearer and more flexible way than the previous version. Unlike the previous JUnit 3-based test method for Android units (using JUnit 4), you do not need to extend the Junit.framework.TestCase class. You do not need to precede the test method name with the "test" keyword, or use any of the classes in the Junit.framework or Junit.extensions package.

To create a basic JUnit 4 test class, you create a Java class that contains one or more test methods. The test method @Test starts with a comment and contains code to practice and validate a single feature in the component to be tested.

The following example shows how to implement a local unit test class. The test method verifies that the emailValidator_CorrectEmailSimple_ReturnsTrue method in the application being tested isValidEmail() returns the correct result.

Import Org.junit.Test;import Java.util.regex.Pattern; import static org.junit.assert.assertfalse;import static org.junit.assert.asserttrue; Public class emailvalidatortest {      @Test      Public void emailvalidator_correctemailsimple_returnstrue< Span class= "Hljs-params" > () {        Assertthat (Emailvalidator.isvalidemail (true));   }    ...}  

To test whether the components in your application will return the expected results, use JUnit. The Assert method performs a validation check (or assertion) to compare the state of the component under test against an expected value. To make the test more readable, you can match the returned results with the expected results using the hamcrest match, such as is () and the Equalto () method.

Mock Android Dependency

By default, the Android plug-in for Gradle will perform local unit testing against the modified version of the Android.jar library, which does not contain any actual code. Instead, call the Android class from your unit test method to throw an exception. This is to make sure that you only test your code and not rely on any specific behavior of the Android platform (you do not explicitly mock).

You can use the mock framework to remove external dependencies in your code to easily test the interaction of components and dependencies in an expected way. By replacing Android dependencies with mock objects, you can separate unit tests from the rest of the Android system and verify that the correct methods are invoked in those dependencies. Java's Mockito Simulation framework (version 1.9.5 and later) provides compatibility with Android unit tests. With Mockito, you can configure mock objects to return a specific value at call time.

To add a mock object to a local unit test using this framework, follow these programming models:

1. Include Mockito library dependencies in your Build.gradle file, as described in setting up the test environment above.

2. At the beginning of the unit test class definition, add a @RunWith(MockitoJUnitRunner.class) comment. This note tells the Mockito Test runner to verify that you are using the framework correctly and to simplify the initialization of your mock objects.

3. To create a mock object for Android dependencies, add the @mock comment before the field declaration.

4. For stub-dependent behavior, you can when() return() specify a condition and return value when the condition can be satisfied by using the and methods.

The following example shows how to create a unit test that uses a simulated context object.

ImportStatic org.hamcrest.MatcherAssert.assertThat;ImportStatic org.hamcrest.corematchers.*;ImportStatic org.mockito.mockito.*;Import Org.junit.Test;Import Org.junit.runner.RunWith;Import Org.mockito.Mock;Import Org.mockito.runners.MockitoJUnitRunner;Import android.content.SharedPreferences;@RunWith (Mockitojunitrunner.class)PublicClassUnittestsample {PrivateStaticFinal String fake_string ="HELLO World";@Mock Context Mmockcontext;@Testpublic void readStringFromContext _localizedstring () {        //Given a mocked Context injected into the object under test...        When (Mmockcontext.getstring (r.string.hello_ Word)                . Thenreturn (fake_string);        Classun Dertest myobjectundertest = new classundertest (mmockcontext);        Span class= "Hljs-comment" >//... when the string was returned from the object under test...        Strin G result = myobjectundertest.gethelloworldstring ();        //... then The result should be the expected one.        Assertthat (result, is (fake_string));   }}        

To learn more about using the Mockito framework, see the Mockito API Reference and Sharedpreferenceshelpertest classes in the sample code.

Error: "Method ... not mocked"

If you run the test and call the API from the Android SDK, you will not use the mock and may receive an error saying that this method has not been simulated. This is because the Android.jar file that is used to run the unit tests does not contain any current code (these APIs are provided only by the Android system image on the device).

Instead, all methods throw exceptions by default. This is to ensure that your unit tests your code, rather than relying on any specific behavior of the Android platform (you do not explicitly mock, such as Mockito).

If the exception that is thrown says you have a problem with your test, you can change the behavior to return null or 0 by adding the following configuration to the project's top-level Build.gradle file:

true  }}

Note: Set the Returndefaultvalues property to true should be careful. The Null/zero return value can introduce regression in the test, which is difficult to debug and may allow failed tests to pass. Only use it as a last resort.

Run a local unit test

To run your local unit tests, follow these steps:

1. Make sure your project is synchronized with gradle by clicking Sync Project in the toolbar.

2. Run the test in one of the following ways:

    • To run a single test, open the Project window, right-click to test, and then click Run.
    • To test all methods in a class, right-click the class or method in the test file, and then click Run.
    • To run all tests in the catalog, right-click the directory and select Run Tests.

Android Test (iv): Local unit Test

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.