Getting started with unit testing for Java4Android

Source: Internet
Author: User

Getting started with unit testing for Java4Android

This article describes how to use the various functions provided by JUnit 4 to conduct effective unit tests, and demonstrates how to use Ant to perform automated unit tests through an example. This article assumes that you have some experience in Java Development in Eclipse and understand the annotation Feature in Java 5.
Introduction

There is no doubt that programmers are responsible for the code they write. You should not only ensure that the code can be compiled and run normally, but also meet the requirements and design expectations. Unit testing is one of the effective methods to verify whether code behavior meets expectations. However, it is undeniable that testing is boring, and testing over and over again is even more daunting. Fortunately, the unit test tool JUnit makes all this simple art.

JUnit is the most well-known unit testing tool in the Java Community. It was born in 1997 and developed by Erich Gamma and Kent Beck. Erich Gamma is one of the authors of the classic book "design patterns: the basis for reusable object-oriented software" and has made great contributions to Eclipse; kent Beck is an expert and pioneer in extreme programming (XP.

The sparrow is small and dirty. JUnit is designed to be very small but powerful. Martin Fowler commented so much on JUnit: in the field of software development, there has never been so little code that plays such an important role. It greatly simplifies the difficulty for developers to perform unit tests. In particular, JUnit 4 makes the test easier by using annotation in Java 5.

JUnit 4 Initial Experience

Before getting started with JUnit 4, we need the support of the following software:

Eclipse: the most popular IDE, which fully integrates JUnit and supports JUnit 4 from version 3.2. Of course, JUnit does not rely on any IDE. You can download the latest Eclipse version from the http://www.eclipse.org.
Ant: a Java-based Open Source build tool that gives you the latest version and rich documentation on http://ant.apache.org. Ant has been integrated in Eclipse, but at the time of writing this article, Eclipse uses a lower version of Ant (1.7 or later versions are required) and does not support JUnit 4 well.
JUnit: its official website is http://www.junit.org /. You can get the latest message about JUnit from above. If you use JUnit in Eclipse like this article, you do not have to download it again.
First, create a Java project named coolJUnit for our experience. What you need to do now is to open the properties page of the Project coolJUnit-> select the "Java Build Path" sub-option-> click "Add Library ..." Click-> in the "Add Library" dialog box that appears, select JUnit (Figure 1), select version 4.1 On the next page, and click "Finish. In this way, JUnit is introduced to the current project library.


Figure 1 Add a JUnit library for the project
Unit Test Tool JUnit4 "title =" javaJUnit4 ">

Note the JDK version.

JUnit 4.1 is an upgraded version based on Java 5. It uses many new features in Tiger to simplify the original usage. Because of this, it cannot run directly on JDK 1.4.x. To use JUnit in JDK1.4.x, use 3.8.1.


Can I start writing unit tests? And so on ......, Where do you plan to place the unit test code? Mixing it with the tested code is obviously messy, because unit test code won't appear in the final product. We recommend that you create separate directories for the unit test code and tested Code respectively, and ensure that the test code and tested Code use the same package name. This ensures code separation and convenient search. Following this principle, we add a new directory testsrc under the project coolJUnit root directory and add it to the project source code directory (see figure 2 ).

Figure 2 modify the project source code directory
Unit Test Tool JUnit4 "title =" javaJUnit4 ">

Now we get a best practice for JUnit: unit test code and tested Code use the same package, different directories.

Everything is ready. Let's get started with how to use JUnit for unit testing. The following example is from the author's development practices: the static method wordFormat4DB in the tool class WordDealUtil is used to process the conversion from a Java object name to a database table name (you can get more details in the code comment ). The following figure shows the general situation after the first encoding is completed:

Java code JUnit4 ">

  1. Package Com. ai92.cooljunit;
  2. Import Java. util. regex. Matcher;
  3. Import Java. util. regex. Pattern;
  4. Public Class WordDealUtil{
  5. Public Static StringWordFormat4DB (StringName ){
  6. PatternP=Pattern. compile ("[A-Z]");
  7. MatcherM=P. matcher (name );
  8. StringBufferSb=New StringBuffer ();
  9. While(M. find ()){
  10. M. appendReplacement (sb,"_" + M. group ());
  11. }
  12. Return M. appendTail (sb). toString (). toLowerCase ();
  13. }
  14. }


    Can it be executed as expected? Try to write the JUnit unit test code for it as follows:

    Java code JUnit4 ">
    1. Package Com. ai92.cooljunit;
    2. Import Static Org. junit. Assert. assertEquals;
    3. Import Org. junit. Test;
    4. Public Class TestWordDealUtil{
    5. // Test the normal operation of wordFormat4DB
    6. @ TestPublic Void WordFormat4DBNormal (){
    7. StringTarget="EmployeeInfo ";
    8. StringResult=WordDealUtil. wordFormat4DB (target );
    9. AssertEquals ("employee_info ",Result );
    10. }
    11. }

      A very common class! The Test class TestWordDealUtil starts with "Test" to better distinguish between the Test class and the tested class. The test method wordFormat4DBNormal calls and executes the tested method WordDealUtil. wordFormat4DB to determine whether the running results have achieved the expected results. Note that the test method wordFormat4DBNormal needs to be written in accordance with certain specifications:

      The Test method must be modified using the annotation org. junit. Test.
      The test method must be modified using public void and cannot contain any parameters.
      The string to be processed in the test method is "employeeInfo". According to the design purpose, the processed result should be "employee_info ". AssertEquals is a series of Static Assertion methods provided by JUnit to determine whether the test results are correct (in the class org. junit. in Assert), we use it to compare the execution result with the expected value "employee_info" to determine whether the test is successful.

      Check the running result. Right-click the Test class and choose Run As JUnit Test from the context menu. Shows the running result:


      Figure 3 successful JUnit operation page
      Unit Test Tool JUnit4 "title =" javaJUnit4 ">

      The green progress bar prompts us that the test has passed. But it is too early to announce that the Code has passed the unit test. Remember: Your unit test code is not used to prove that you are right, but to prove that you are not wrong. Therefore, the Unit Test scope should be comprehensive, such as testing the boundary value, normal value, and error value; and comprehensively predicting possible problems in the code, this is exactly what needs to be considered in the demand analysis and detailed design processes. Obviously, our test is just starting. We will continue to add some tests for special cases:

      Java code
      1. Public Class TestWordDealUtil{
      2. ......
      3. // TestNullProcessing status
      4. @ TestPublic Void WordFormat4DBNull (){
      5. StringTarget=Null;
      6. StringResult=WordDealUtil. wordFormat4DB (target );
      7. AssertNull (result );
      8. }
      9. // Test the handling of null strings
      10. @ TestPublic Void WordFormat4DBEmpty (){
      11. StringTarget="";
      12. StringResult=WordDealUtil. wordFormat4DB (target );
      13. AssertEquals ("",Result );
      14. }
      15. // Test the case where the first letter is capitalized
      16. @ TestPublic Void WordFormat4DBegin (){
      17. StringTarget="EmployeeInfo ";
      18. StringResult=WordDealUtil. wordFormat4DB (target );
      19. AssertEquals ("employee_info ",Result );
      20. }
      21. // Test the case where the last letter is in uppercase
      22. @ TestPublic Void WordFormat4DBEnd (){
      23. StringTarget="Maid ";
      24. StringResult=WordDealUtil. wordFormat4DB (target );
      25. AssertEquals ("maid ",Result );
      26. }
      27. // Test the upper case of multiple connected letters
      28. @ TestPublic Void WordFormat4DBTogether (){
      29. StringTarget="EmployeeAInfo ";
      30. StringResult=WordDealUtil. wordFormat4DB (target );
      31. AssertEquals ("employee_a_info ",Result );
      32. }
      33. }


        Run the test again. Unfortunately, the JUnit running interface prompts us that two tests failed (figure 4) -- The processing result obtained when the first letter is capitalized is different from the Expected One, A test failure occurs. When the test results are null, an exception-test error is thrown ). Obviously, the code to be tested does not process uppercase letters or null. The changes are as follows:

        Java code JUnit4 ">
        1. // The modified wordFormat4DB Method
        2. Public Static StringWordFormat4DB (StringName ){
        3. If(Name=Null){
        4. Return Null;
        5. }
        6. PatternP=Pattern. compile ("[A-Z]");
        7. MatcherM=P. matcher (name );
        8. StringBufferSb=New StringBuffer ();
        9. While(M. find ()){
        10. If(M. start ()! =0)
        11. M. appendReplacement (sb,("_" + M. group (). toLowerCase ());
        12. }
        13. Return M. appendTail (sb). toString (). toLowerCase ();
        14. }


          Figure 4 JUnit operation failure page
          Unit Test Tool JUnit4 "title =" javaJUnit4 ">

          JUnit divides the test failure into two types: failure and error. Failure is generally caused by the assertion method used by the unit test to identify Failure. It indicates that a problem has been found in the test point, and error is caused by code exceptions, which are not found in the test Purpose, it may be caused by an error in the test code itself (the test code is also code and cannot be guaranteed to have no defects at all), or it may be a hidden bug in the test code.

          Please remember!

          Keep this JUnit best practice in mind: Test any possible errors. Unit testing is not used to prove that you are right, but to prove that you are not wrong.

          Aha, run the test again, and the green strip reappeared. Through comprehensive unit tests on WordDealUtil. wordFormat4DB, the current code is relatively stable and can be provided to other modules as part of the API.

          Unconsciously, we have completed a unit test with JUnit. We can understand how lightweight and simple JUnit is and don't need to worry about it at all. This allows us to focus more on more meaningful things-writing complete and comprehensive unit tests.

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.