Step by gradual learning JUnit

xiaoxiao2021-03-06  41

Use the most popular open resource test framework learning unit test basis.

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.parseexception;

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, turn on 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 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.

Write a JUnit test instance

You have seen the source code of 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);

Compile and run test now:

$ 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 increased row statements:

Throw New Exception ("this is a test");

Then compile and run the test:

$ javac * .java $ junit.textui.teestrunner isodatetest

.

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 be called to make the test fail, the method is as follows:

Public void testIndexOutofbounds () {

Try {

ArrayList List = New ArrayList ();

List.get (0);

Fail ("IndexOfboundsexception

");

} catch (indexoutofboundsexception e) {}

}

JUnit's advanced features

In the sample 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 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.

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

New Post(0)