Step by gradual learning JUnit

xiaoxiao2021-03-06  62

Using JUnit can reduce the number of program errors in Java code, Junit is a popular unit test framework for unit testing of it before publishing code. Let us now study how to use tools such as JUnit, Ant and Oracle9i JDeveloper to write and run unit tests. Why use JUnit? Most developers agree to test them before publishing the code, and use the tool to regression. A simple way to do this is to implement a test in a Main () method in all Java classes. For example, assume that use ISO format (which means there is a subclass of a Date to write a Date as a constructor as a parameter and a TOSTRING () method returning a formatted ISO string) and a GMT time zone. Listing 1 is a simple implementation of this class. However, this test method does not require a Qualifier, which is as follows:

The minimum unit for testing in a class is a method, you should test each method separately to accurately find which methods work is normal, which methods are not working properly. Even if the test fails in front, each method should also be tested. In this implementation, if a single test fails, the later test will not run at all. This means that you will not know the percentage of bad code in your implementation. Test code will appear in the generated class. This may not have problems in size in size, but it may become one of the security factors: For example, if your test embeds the database connection password, this information will be easily used in the published class. No framework can be automatically launched, you must write a script to launch every test. When writing a report, you must write your own implementation and define a rule to easily report an error. The JUnit framework is designed to solve these problems. This framework is mainly a parent class (called "TestCase"), and provides a tool to run the test, generate a report, and definition test package (TEST Suite). Let us write a test for the IsoDate class: This isodatetest class is similar to: import java.text.parsexception;

Import junit.framework.testcase;

/ **

* Test case for isodate .

* /

Public class isodatetest extends testcase {

Public void testisodate () THROWS

EXCEPTION {

Isodate ePoch = new isodate

"1970-01-01 00:00:00 GMT");

Assertequals (0, EPOCH.GETTIME ());

Isodate Eon = New isodate

"2001-09-09 01:46:40 GMT");

askERTEQUALS

1000000000L * 1000, Eon.gettime ());

}

Public void testtotring () throws

Parsexception {

Isodate ePoch = new isodate (0);

askERTEQUALS ("1970-01-01

00:00:00 GMT ", EPOCH.TOSTRING ());

Isodate Eon = New isodate

1000000000L * 1000);

Assertequals ("2001-09-09

01:46:40 gmt ", eON.toString ());

}

The focus of attention in this example is that a separate class for testing has been written, so these files can be filtered to avoid embed this code into the document to be published. In addition, this example also writes a dedicated test method for each method you want to test in your code, so you will know which methods need to be tested, which methods are working properly and what methods are not working properly. If you have written this test before writing a document, you can take advantage of its progress. Install and run JUnit To run this sample test instance, you must first download and install JUnit. The latest version of JUnit can be downloaded for free at the JUnit website www.junit.org. The package is small (about 400 kB), but in which source code and document are included. To install this procedure, the package should first decompress the junitxxx.zip. It will create a directory (junitxx), in this directory (in the doc directory), the framework application programming interface (API) document (in the javadoc directory), run the program library file (JUnit.jar), Test instance (in the junit directory). As of this writing this article, JUnit's latest version is 3.8.1, I am tested on this version.

Figure 1 Run the isodate test

To run this test instance, copy the source file (isodate.java and isodatetest.java) to the JUnit installation directory, open the terminal, enter the directory, then enter the following command line (if you are using UNIX): export classpath =. : ./ junit.jar

Javac * .java

Or, if you are in Windows, enter the following command line

Set classpath = .; junit.jar

Javac * .java

These command lines set ClassPath to include classes in the current directory and JUnit.jar libraries, and compile Java source files. To run the test on the terminal, enter the following command line: java junit.textui.teestrunner isodatetest

This command line will run the test and display the test results on the console shown in Figure 1. This tool can run the class name to be passed to a single test in the command line. Note: Only the last test of the command line is considered, the previous test is ignored. (It looks like a program error, is it?) JUnit also provides a graphical interface that utilizes the AWT (Abstract Window Toolkit) or Swing. In order to run the test with this graphical interface, enter the following command line on the terminal: java junit.awtui.teestrunner isodatetest

Or use the Swing interface: java junit.swingui.teestrunner isodatetest

This command line will display the interface shown in Figure 2. To select a test and run it, click the button with three points. This will display ClassPath (also test packets, but we will discuss all the tests in the following. To run the test, click the "RUN" button. The test should be operated correctly and the results are displayed in the interface shown in Figure 2. In this interface, you should be selected in the selection check box "RELOAD CLASSES EVERY RUN" so that the runtime will reload them before running the test class. This makes it easy to edit, compile and run the test, without having to start the graphical interface each time. The following is a progress bar under this check box, which is very useful when running a larger test package. Running tests, errors, and failures are displayed under the progress bar. Then there is a failed list and a test hierarchy. Failure messages are displayed at the bottom. You can run a single test method by clicking the Test Hierarchy panel, then click the "Run" button in the upper right corner of the window. Keep in mind that using the command line tool is not possible to do. Note that these classes must exist in the classpath when the tool is running to start the test class. But if the test class is stored in the JAR file, even if these JAR files exist in classpath, JUnit can't find these test classes. Figure 2 Swing interface for running the test

This is not a convenient way to start testing, but fortunately, JUnit has been integrated into other tools (such as Ant and Oracle9i JDeveloper to help you develop tests and make tests automatically. Writing a JUnit test instance You have seen the source code for the test class to ask about IsoDate implementation. Now let us study the implementation of such test documents. The test instance is inherited by junit.frameword.testcase to use the JUnit framework. The name of this class is attached to "Test" on the name of the test class. Because you are testing a class named IsoDate, the name of its test class is isodatetest. In order to access all methods other than private methods, this class is usually in the same package with the measured class. Note that you must write a method for each method you want to test in the class. You want to test the constructor or use the ISO date format, so you will need to write a test method for the constructor and the toString () method for the string of the ISO format. Its naming mode is similar to the test class: "Test" is attached to the front of the test method (or constructor). The subject of the test method is inquiry by verifying the ASSERTION (assertion). For example, in TOSTRING () implementation test methods, you want to confirm that the method has made a good description of time (for UNIX systems, the initial introduction is midnight on January 1, 1970) . To implement Assertion, you can use the Assertion method provided by the JUnit framework. These methods are implemented in the JUnit.framework.assert class of the frame, and can be accessed in your test because Assert is the parent class of TestCase. These methods can be compared to keyword assert in Java (which is new in J2EE 1.4). Some Assertion methods can check if the original type (such as Boolean, integer, etc.) or whether the object is equal (using the equals () method to check if the two objects are equal). Other ASSERTION methods Check if the two objects are the same, whether an object is "empty" or "non-empty", and a Boolean value (usually generated by an expression) is "true" or "false". These methods are summarized in Table 1. For those ASSERTION that uses floating point types or double precision type parameters, there is a third method, that is, a Delta value is used as a parameter. Also note that assertequals () and assertsame () methods generally do not produce the same results. (The two strings having the same value can be different because they are different objects with different memory addresses.) So, Assertequals () will verify the validity of Assertions, and assertsame () will not. Note that for each Assertion method in Table 1, you have another choice, which is to introduce another parameter. If the assertion fails, this parameter gives a explanatory message. For example, Assertequals (INT desired value, int actual value) can be used with a message such as Assertequals (string messages, int desise, int actual value). When an assertion fails, the Assertion method throws an AssertFailerror or ComparisonFailure.

AssertionFaileDError is inherited by java.lang.Error, so you don't have to declare it in the THROWS statement of the test method. ComparisonFail is inherited by AssertionFaileDerror, so you don't have to declare it. Because when an assertion fails, an error is thrown in the test method, so the next Assertion will continue to run. The frame captures these errors and identifies that the test is printed to print a message. This message is generated by assertion and is passed to the assertion method (if any). Now add the following row statements to the end of the Testisodate () method: Assertequals ("this is a test", 1, 2); now compile and run test: $ javac * .java

$ java junit.textui.teestrunner isodatetetest

.

Time: 0,348

There WAS 1 Failure:

1) TestisoDate (isodatetest) JUnit.framework

.Assertionfailederror: this is a test experted: <1> But Was: <2>

At isodatetest.testisodate

(Isodatetest.java: 29)

Failures !!!

Tests Run: 2, Failures: 1, Errors: 0

JUnit prints a point for each processed test, showing the letter "f" to indicate failure and displays a message when the assertion fails. This message consists of the comments you sent to the Assertion method and the result of Assertion (automatically generated). From here you can see that the parameter sequence of the Assertion method is very important for the generated message. The first parameter is a desired value, and the second parameter is the actual value. If a certain error occurs in the test method (for example, an exception throws an exception), the tool will display it as an error (not a "failed" that is generated by the assertion failure). Now modify the ISODATETEST class to replace the previously added row statements instead of: Throw new Exception ("this is a test");

Then compile and run test: $ javac * .java

$ java junit.textui.teestrunner isodatetetest

.

Time: 0,284

There was 1 error:

1) TestisoDate (isodatetest) java.lang.

Exception: this is a test at isodate

Test.testisodate (isodatetest.java: 30)

Failures !!!

Tests Run: 2, Failures: 0, Errors: 1

This tool displays the exception as an error. Therefore, an error represents an error test method, rather than representing an error test implementation. The ASSERT class also includes a FAIL () method (this version with interpretive messages), which will interrupt the running test by throwing AssertionFaileDError. The fail () method is very useful when you want a test failure without calling a judgment method. For example, if a piece of code should throw an exception without throw, then the fail () method can make the test fail, the method is as follows: public void testexoutofbounds () {TRY {

ArrayList List = New ArrayList ();

List.get (0);

Fail ("IndexOfboundsexception

");

} catch (indexoutofboundsexception e) {}

}

JUnit's advanced features In the example test instance, you have run all the tests at the same time. In reality, you may want to run a given test method to ask you to write the implementation method you are writing, so you need to define a group to run. This is the purpose of the framework's JUnit.framework.testsuite class, which is actually just a container, you can add a series of tests to it. If you are performing toString () implementation, and want to run the corresponding test method, you can notify the operator by overwriting the suite () method of the test, the method is as follows: public static test suite () {

Testsuite suite = new testsuite ();

Suite.Addtest (New IsodateTest)

("TestTString")))

Return suite;

}

In this method, you describe a TestSuite object with a specific example and add a test. In order to test the method level definition, you can use the constructor to instantiate the method name as a parameter. This constructor can be implemented as follows: public isodatetest (String name) {

Super (Name);

}

Add the above constructor and method to the IsoDateTest class (also need to introduce junit.framework.test and junit.framework.testsuite) and enter: on the terminal:

Figure 3: Select a test method

$ javac * .java

$ java junit.textui.teestrunner isodatetetest

.

Time: 0,31

OK (1 test)

Note that in the test method added to the test package, only one test method is run, that is, the toString () method. You can also use the graphical interface to run a given test method by selecting a test method in Figure 3 in the Test Hierarchy panel shown in Figure 3. However, it is important to note that the panel will be filled after the entire test package is running once. When you want to add all test methods in a test instance to a TestSuite object, a dedicated constructor can be used, which uses the class object of this test instance as a parameter. For example, you can implement Suite () methods using the isodatetest class, the method is as follows: Public static test suite () {

Return New TestSuite (isodatetest.class);

}

There are also situations that you might want to run a set of tests consisting of other tests (such as all tests before the project). In this case, you must write a class that implements the Suite () method to establish a test package that you want to run. For example, assuming that you have written test class ATEST and BTEST. In order to define those collections that contain all the tests in class ATest and test packages defined in BTEST, you can write the following classes: import junit.framework. *; / **

* Testsuite That Runs All Tests.

* /

Public class alltests {

Public static test suite () {

Testsuite Suite = New Testsuite ("All Tests");

Suite.addTestSuite (Ateest.class);

Suite.addtest (btest.suite ());

Return suite;

}

}

You can run this test package like running a single test instance. Note that if a test is added twice in a kit, the runner will run it twice (the test package and the runner do not check if the test is unique). In order to understand the implementation of the actual test package, it should be to study the test package of Junit itself. These types of source code exist in the JUnit / Test directory of the JUnit installation.

Figure 4: Report showing test results

Sometimes it is sometimes very convenient to add a main () method to a test or a test package, so the test can be started without using the runtime. For example, to start the AllTests test package as a standard Java program, you can add the following main () method to the class: public static void main (string [] args) {

Junit.textui.teStrunner.run (Suite ());

}

You can now start this test package by entering Java AllTests. The JUnit framework also provides an effective way to use the code that intends to set resources to objects called fixture. For example, the sample test instance utilizes two references called EPOCH and EON. Re-compiling these dates is only wasted in each method test (and there may be errors). You can rewrite tests with fixture, as shown in Listing 2. You define two reference dates as a segment of the test class, and compile them into a setup () method. This method is called before each test method. The method corresponding to it is the Teardown () method, which will clear all resources after each test method (in this implementation, the method does not do, because the garbage collector has completed this work for us) . Compile this test instance (its source code should be placed in the JUnit installation directory) and run it: $ javac * .java

$ java junit.textui.teestrunner isodatetest2

.Setup ()

TestisoDate ()

TEARDOWN ()

.Setup ()

TestTostring ()

TEARDOWN ()

Time: 0,373

OK (2 tests)

Note: Reference date is established in this test instance, so modifying these dates in any test method will not adversely affect other tests. You can put the code in both ways to build and release the resources you need for each test (such as database connections). The JUnit publishing also provides an extended mode (in the package junit.extensions), which is Test Decor-Ators to provide new features like repeatedly run a given test. It also provides a TestSuite to facilitate you to run all tests simultaneously in a separate thread and stop when testing in all threads. Step-by-step learning JUnit: The second part uses ANT to make test automation as described earlier, the test runner is very original. If you are running Ant to compile your project, the compilation file is a good way to run unit test. (For the introduction of Ant, please refer to my article "Ant Introduction" (Starting With Ant), published in Oracle Magazine from 11/12 months. Suppose your source file is in the src directory, the generated class is in the TMP directory, and the junit.jar library is in the libdirectory directory of the project, then you can compile the Java source file and use the compilation file shown in Listing 3 ( In the root of the project) running unit test. The core of this compilation file is the test target for running unit tests. Running these tests is the only task of this target JUnit. In order to run this optional task, you must first put the junit.jar library into the lib directory in the Ant installation directory, then download and install the ANT optional task libraries in the same directory. The example in Listing 3 nested a ClassPath class, which includes a JUnit library and a class; an example is also nested in the example, which uses a FileSet element that selects the appropriate source file defines the test that will run. This task also includes Haltonfilure and HaltonError properties, which tell ANT whether they should stop when encountering a failure or error. If you set their values ​​to "true", Ant will stop when you encounter the first failure or error, and compile will fail (obviously, this means there is a problem during the running test). On the other hand, if the value is set to "false", the result is not very clear (even if the test fails, the compilation will succeed), but all tests will continue. The PRINTSUMMARY attribute indicates whether the ANT displays the output of the run test. Numerical withoutanderr can easily tell ANT display standard output and error output when developing testing. The value OFF indicates that no content is displayed, while the ON only displays the test report (no test class output). The JUnit Task has a lot of properties, please refer to the ANT documentation for details. To test this compilation file, you need to create a directory named SRC, TMP, and LIB. Place the junit.jar library into the lib directory and place the sample java source file as seen in the SRC directory. Open the terminal, enter the root directory of the project, and enter Ant, the result is: $ ANT

Buildfile: build.xml

Clean:

DELETING DIRECTORY

/ Users / Casa / Doc / Oracle

/ junit / prj / TMP

[mkdir] create Dir: / Users / Casa

/ DOC / ORACLE / JUnit / Prj / TMP

BIN:

[Javac] Compiling 4 Source Files

To / users / Casa / Doc / Oracle

/ junit / prj / tmptest:

[junit] Running isodatetest

[JUnit] Tests Run: 1, Failures:

0, Errors: 0, Time Elapsed:

0,005 sec

[junit] Running isodatetest2

[JUnit] Tests Run: 2, Failures: 0,

Errors: 0, Time Elapsed: 0,031 sec

[junit] Output:

[junit] setup ()

[junit] Testisodate ()

[junit] Teardown ()

[junit] setup ()

[junit] TestTString ()

[junit] Teardown ()

All:

Build Successful

Total Time: 8 seconds

Ant can also generate a very useful test report for HTML format. In order to generate such a report, use the previous test target instead:

Description = "Run Junit Tests">

PRINTSUMMARY = "withoutanderr">

INCLUDES = "** / * test * .java" />

Includes = "Test - *. xml" />

Todir = "$ {TMP}" />

This goal is the same as the front goals, just the target adds a new attribute in the BatchText element, which tells Ant to generate an Extensible Markup Language (XML) report in the TMP directory. This goal also adds a new JUnitReport element to generate an HTML report by an XML file. This element requires the installation of the Xalan library in the lib directory where Ant is installed (see the JunitReport section of the ANT document: ant.apache.org/manual/install.html). This element also defines the target directory of files generated using the Todir property. The XML file that needs to be processed by nested a Fileset element to generate this report. The desired output format is implemented using nested report elements. This object will generate a report such as the report shown in Figure 4. Such reports are particularly useful when the unit is automatically run (such as during the night compilation). In these cases, errors or failures do not interrupt the test, so you must set the HaltonFailure and HaltonError properties of the JUnit tasks mentioned earlier to "false". This report is also very useful for measuring the implementation process (such as when you have to rewrite the code, or before the implementation has been prepared). Ant is also very useful to start JUnit graphics runners. The following object will start SWING test runner:

ClasspathRef = "cp"

Fork = "true" />

You should run this object in the terminal and compile it using Ant in another terminal or in the IDE you like. This way allows you to start the graphic runner every time you want to test the code. JUnit integration in Oracle9i JDeveloper Oracle9i JDeveloper is not based on network integration JUnit, but only a few minutes of downloading and installing this plugin. In order to complete this process, select the "Check for Updates" item under the "Help" menu of JDeveloper. This will open the IDE update wizard to connect to the Oracle technology website, download the plugin and install it. When the plugin is installed, you need to turn off and restart Oracle9i JDeveloper. Note that the wizard also downloads the relevant documentation. By providing a wizard for each task, this plugin greatly improves the work efficiency of developers writing test instances, test packages, and fixture. To call these wizards, click the "New" item under the "File" menu, then select the "General / Unit Tests" class and select the appropriate wizard from the right form. You can also start the test suite from the interface. When you are ready to test the project, you should first use the dedicated wizard to write FixTure, and then the test instance will be used to integrate into the test instance. In addition, some wizards used to generate custom test fixture and the wizard of generating business components and database connections to test fixture. These two wizards generate a dedicated code to use the setup () and Teardown () methods to set up and publish business components or database connections. When FixTure is completed, the next step should use the appropriate wizard to generate a test instance, which allows you to select the classes and methods to test. You can also choose FixTure used in this test. This will generate a code framework that uses the body of the test method. Finally, the kit should be generated to run your test. This dedicated wizard allows you to choose the test to be included in the suite and generate the entire class for you. To launch a test suite, click the file in the browser and select Run. This will start the graphical interface and run the kit. Select "Help Topics" in the "Help" menu, you will find a detailed tutorial for how to use these wizards in the JDeveloper documentation. This will open the help system window. Click the "Unit Testing with Junit" item and select the appropriate tutorial. This integration between JUnit and JDeveloper enables you to write only the code you interested in the unit test, and let the tool write repeated code for you. Next step

Visit the JUnit website www.junit.org Download Oracle9i JDeveloperotn.racle.com/software/products/JDev / Oracle9i Application Server OTN.Oracle.com/software/products/ias/ Learn Oracle9i JDeveloper Extension Otn.racle.com/products/JDEV / HTDOCS / Partners / Addins Read Oracle9i JDeveloper Document Otn.Orcle.com/docs/products/jdev/ JUnit Best Practice Before using JUnit, you should pay attention to:

Write test code before implementation. This is an implementation of a contract-driven implementation. Only methods that may be interrupted (that is, in most cases, the setter and getter methods should not be tested. Test as much as possible to avoid regression tests. When testing a larger application, you can run all tests at night. Be sure to use the correct JUnit extension to test special applications (such as using the Castus test J2EE application). It is worth spending to now, you should clearly know how fast the unit testing uses the JUnit framework and the appropriate tool implementation unit test. About the next goal of the unit test is to make your CTO believe that you must spend more time in implementing tests. However, when you consider checking the old code, correcting errors, and publishing a debugged version (it might cost the whole day), the code error in the early stage of the development process is undoubtedly a very good. Good investment. Here is not considered when the error code is no longer located at the top of the block, the developer must follow the "Black Magic" step, including: tag code, making a branch, correcting code error, release, and incorporate code correction into blocks in. All of these steps are very time consuming, and it is easy to generate errors. To start using unit testing and junit, visit the JUnit website: www.junit.org. You will find a large number of useful documents (including detailed manuals using JUnit implementation test), a list of IDE integrated with JUnit, and details about the JUnit extension tool. Michel Casabianca (CASA@sweetohm.net) is a software engineer in IN-FUSIO (a French company that provides game service for mobile users), as well as the computing of XML Pocket Reference (O'Reilly Publishing, 2001) . Table 1: Writing the determination method used in the test example

Assertequals (desired prototype, actual prototype) Check if the two prototypes are equal, assertequals (desired object, actual object) use the object's equals () method to check if the two objects are equal assertsame (desired object, actual object) check two of the same memory address. Whether an object is equal assertnotsame (desired object, actual object) Check if two objects with different memory addresses Assertnull (Object Object) Check if an object is empty AssertNotnull (Object object) Check if an object is non-empty ASSERTRUE (Boole Conditions) Check the conditions for true Assertfalse (Boolean conditions) inspection conditions are false

转载请注明原文地址:https://www.9cbs.com/read-89353.html

New Post(0)