JUnit JUnit developer of learning step by step: Michel Casabianca use one of the most popular open source test basis learning unit testing framework. 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. The reason is as follows: The minimum unit for testing in a class is a method, you should test each method separately to accurately find what method work 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's 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"); assertequals (1000000000L * 1000, eON.gettime ());} PUBLIC VOID TESTOSTOSTRING () THROWS PARSEEXCEPTION {isodate EPOCH = New Isodate (0 ("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 should be paid attention to in this example is the independent class for testing, so these files can be filtered to avoid embed this code into the document to be released. in. 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 Running 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) : ./ junit.jar javac * .java or, if you are in Windows, enter the following command line set classpath = .; junit.jar javac * .java These command lines are set to ClassPath, so that they contain current Category and JUnit.jar libraries in the catalog, and compile the Java source file. To run the test on the terminal, enter the following command line: Java junit.textui.teStrunner 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 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 test This is not a convenient method of starting testing, but fortunate is that JUnit has been integrated into other tools (such as Ant and Oracle9i JDeveloper) to help you develop tests and make tests automatic running. 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 isodatetest .f. Time: 0,348 There was 1 failure: 1) testIsoDate (IsoDateTest) junit.framework .AssertionFailedError: This is a test expected: <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 display 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: throw new exception; then compile and run test: $ javac * .java $ java junit.textui.teestrunner isodatetest 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 invoke the test fails, the method is as follows: public void testexoutofbounds () {try {arraylist list = new arraylist (); list.get ( 0); Fail ("INDEXOFBOUNDSEXCEPTION NOT THROWN");} 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 rewriting the suite () method of the test, the method is as follows: Public static test suite () {testsuite suite = new testsuite Suite.addtest ("TestTString"); Return Suite;} In this method, you describe a TestSuite object with a specific example and add a test to it. 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 on the terminal: Figure 3: Select a test method $ javac * .java $ junit.textui.teestrunner isodatetest. Time: 0,31 ok (1 test) Note that in the test method added to the test package, Only a 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 use the ISODateTest class to implement Suite () methods, the method is as follows: public static test suite () {return new testsuite (isodatetest.class);} There are still some cases, you may want to run a set of other tests (if All tests before the project released). 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 test packages in class ATest and test packages defined in BTEST: Import junit.framework. *; / ** * Testsuite That Runs All Tests. * / Public Class Alltests {PUBLIC STATIC TEST Suite () {Testsuite Suite = New Testsuite ("all tests"); suite.addtestsuite; suite.addte (btest.suite ()); return suite;}} You can run like run Single test instance runs this test package. 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 the test results Add a main () method to a test or a test package is sometimes very convenient, so you can start the test 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.teestrunner.run (Suite () );} You can now start this test package by entering Java Allteests. 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).