Introduction and use of unit tests

Source: Internet
Author: User

1. Function of Unit test:

Many developers have a habit and are often reluctant to write a simple unit test program to validate their code. have been very confident about their own procedures, or the existence of a fluke after each run passed directly to the Test team test. However, every time a bug in the test group is submitted, it can be found that there are many other vulnerabilities that have not been thought about in your program. But every time after the bug modified the good luck, think this time there will be no bug. And then again confidently submitted, and the result was defeated. In fact, in the process of project development, the actual programming time is not particularly much, and the really time-consuming is often the debugging and modification phase. Therefore, the coverage of unit tests is necessary.

It is generally believed that unit testing has four functions:
(1) so that the code can be assured of modification and reconstruction;
(2) forcing the programmer to design the software module from the perspective of the caller rather than the creator;
(3) Forcing programmers to write software modules easy to test and invoke, which facilitates decoupling;
(4) The test itself can be used as a description of the code being measured, thereby replacing some of the document functionality.

2. JUnit Unit Test Framework: 2.1. Brief introduction:

JUnit is an open-source test framework for writing and running repeatable automated tests, allowing us to ensure that our code works as expected. JUnit is widely used in the industry and can be used as a separate Java program (at the command line) or within an IDE such as Eclipse. JUnit offers:

    • The assertion tests the expected results.
    • The test function shares common test data.
    • Test suites organize and run tests easily.
    • Graphics and text test runs.
2.2. Easy to use: 2.2.1 Download and install

So far the latest version is JUNIT4, and many Ides are integrated. If you do not have the ability to download these two packages import

    • junit.jar
    • hamcrest-core.jar
2.2.2. JUnit annotations

2.2.3. JUnit assertions

2.2.4. Simple example

Caculate.java:

 Public class caculate {    int Add (intint  numberb) {        return Numbera + Numberb;}    }

Caculatetest.java:

Import Staticorg.junit.Assert.assertEquals;ImportOrg.junit.Before;Importorg.junit.Test; Public classCaculatetest {Privatecaculate caculate; @Before Public voidinit () {if(Caculate = =NULL) {caculate=Newcaculate (); }} @Test Public voidTestadd () {intresult = Caculate.add (5, 3); Assertequals (8, result); }}

Right-click on the Caculatetest.java run as--and JUnit Test:

3. Unit test in Android 3.1. Android Unit Test framework

Based on JUnit, Android has written a set of test frameworks (instrumented test) to support its unit and acceptance tests. Class inheritance Relationships:

3.2. Simple example

With this framework, you can use the test prefix directly in front of the method you are testing without using junit annotations. By inheriting these base classes as needed, we can write the unit tests we need. The Android Studio project automatically generates a Src/androidtest/java folder, and the Unit test class is placed under this folder, with the following directory structure:

Create a new Mainactivity.java under the Src/main/java/com/junittest package, which has a button and a text that can be changed after the button is clicked.

 Public classMainactivityextendsActivity {PrivateTextView Mtextview; PrivateButton Msubmitbutton; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); }    Private voidInitview () {Mtextview=(TextView) Findviewbyid (R.id.hello_text); Msubmitbutton=(Button) Findviewbyid (R.id.submit_button); Msubmitbutton.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Mtextview.settext ("Change from click!");    }        }); }     PublicString gettextstring () {if(Mtextview! =NULL){            returnMtextview.gettext (). toString (); }        return""; }}

Create a new Mainactivitytest.java under the Src/androidtest/javacom/junittest package, mainactivitytest inherit instrumentationtestcase:

 Packagecom.junittest;Importandroid.content.Intent;Importandroid.test.InstrumentationTestCase;ImportAndroid.util.Log;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;/*** Created by Caihanyuan on 15-10-28.*/ Public classMainactivitytestextendsInstrumentationtestcase {Final StaticString TAG = mainactivitytest.class. GetName (); Privatemainactivity mactivity; PrivateTextView Mtextview; PrivateButton Mbutton; /*** Process some initialization work before unit test starts *@throwsException*/@Overrideprotected voidSetUp ()throwsException {Intent Intent=NewIntent (); Intent.setclassname ("Com.junittest", mainactivity.class. GetName ());        Intent.setflags (Intent.flag_activity_new_task); Mactivity=(mainactivity) getinstrumentation (). Startactivitysync (Intent); Mtextview=(TextView) Mactivity.findviewbyid (R.id.hello_text); Mbutton=(Button) Mactivity.findviewbyid (R.id.submit_button); }    /*** Handle Some resource release work after unit test *@throwsException*/@Overrideprotected voidTearDown ()throwsException {mactivity.finish (); Super. TearDown (); }     Public voidTestinit () {assertnotnull (mactivity);        Assertnotnull (Mtextview);    Assertnotnull (Mbutton); }     Public voidTestgettext () {String textstring=mactivity.gettextstring (); Assertequals ("Hello world!", TextString); }     Public voidTestchangetext () {assertnotnull (Mtextview); Getinstrumentation (). Runonmainsync (NewRunnable () {@Override Public voidrun () {Mtextview.settext ("Atest"); Assertequals ("Atest", mactivity.gettextstring ());    }        }); }     Public voidTestclickbutton () {assertnotnull (Mbutton); Getinstrumentation (). Runonmainsync (NewRunnable () {@Override Public voidrun () {Mbutton.performclick (); Assertequals ("Change from click!", mactivity.gettextstring ());    }        }); }     Public voidtestgetactivity () {log.d (TAG, Mactivity.getpackagename ()); }}

Test results:

Due to the limited space, here is just a simple introduction, the Android test framework for the use of the various base classes can refer to the official website.

3.3. Unit Test Framework Robolectric

Robolectric is a framework this allows you to the write unit tests and run them on a desktop JVM while still using an Droid API. Robolectric mocks part of the Android framework contained in the android.jar file. This was similar to the unit test support via the Android Gradle plug-in but Robolectric provides also implementations for The methods while the Android unit testing support throws exceptions in all in Android.jar methods which is used for unit Testing.

So Robolectric is designed so that we can do the Android unit test directly on the local JVM, so we don't have to wait for the Android real machine or emulator to package, install, and run the process. Greatly improves the efficiency of unit testing.

Robolectric's introduction and use of space is longer, here is not written out. References are attached to the relevant information, interested students can see OH.

Reference documents:

Benefits of Unit Testing: http://www.blogjava.net/square/articles/158103.html

JUnit Official website: http://junit.org/

Android Unit test: http://developer.android.com/intl/zh-cn/training/activity-testing/index.html

Robolectric Official website: http://robolectric.org/

Introduction and use of unit tests

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.