[Test] JUnit best practices


What is JUnit?
cherami
JUnit is an open source the Java testing framework used to write and run repeatable tests.He is a system of xUnit unit testing framework for an instance (for java language).It includes the following features:
1, for testing expected results of the assertion (Assertion)
2, for sharing common test data test tools
3, for the convenience of the organization and operation of the test suite tests
4, graphics and text test runner
JUnit was originally developed by Erich Gamma (GoF One) and Kent Beck (xp and one of the pioneers refactor) prepared.
Should be noted that junit is generally used for unit testing, and therefore need to understand the internal structure of the code being tested (so-called white-box testing), the other is xp junit programming and refactoring (refactor) was strongly recommendedtools, automatic unit testing because the circumstances can greatly increase the efficiency of development, but in fact is writing test code takes a lot of time and effort, then the benefits of using this stuff Where is it?I believe that is this:
1, for xp programming, calls for the writing tests before writing code, which can force you to think properly before writing the code in the code (methods) of the function and logic, or write the code is unstable, then you need while maintaining thetest code and the actual code, this workload will increase significantly.Therefore, in xp programming, the basic process is this: the idea - "write test code -" to write code - "test, and writing tests and writing code are incremental, and write a little test that code in the preparation of futureIf problems are found more blocks can be traced to the problem, reduce the difficulty of correcting the error return
2, for the reconstruction, its benefits and xp programming is similar, because the reconstruction is also required to change a little test, less time consuming due to return errors.
3, for non-above two situations, when we develop the appropriate use of write junit test is necessary, because the general test we also need to write code, you may not use the original junit, if you are using junit, but also againstInterface (methods) to prepare test code will reduce future maintenance work, such as changes within the method after (this is equivalent to reconstruction work.)Junit assertion because there is another function, if the test results do not pass the test will tell us that do not pass, why, and if the previous general practice is to write some test code is to look at their output, and then to determine by themselves the results of using the correctusing junit advantage is that this result is correct to judge it to complete, we only need to look at it the right to tell us whether the results can, in general, will greatly improve efficiency.
JUnit Getting Started
cherami order
Installing JUnit
Installation is very simple, first the following address to download a new zip package:
http://download.sourceforge.net/junit/
After downloaded, extract to your favorite directory, the assumption is JUNIT_HOME, then JUNIT_HOME junit.jar under the package added to your system CLASSPATH environment variable, for the IDE environment, the need for increased use of the junit projectlib, its different IDE settings have different settings, where not much to say.
How to use JUnit to write tests?
The simplest example:
1, create a subclass of TestCase:
package junitfaq;
import java.util .*;
import junit.framework .*;
public class SimpleTest extends TestCase {
public SimpleTest (String name) {
super (name);
}
2, write a test method assert the expected results:
public void testEmptyCollection () {
Collection collection = new ArrayList ();
assertTrue (collection.isEmpty ());
}
Note: JUnit test approach is recommended as the beginning of the method to be tested, so that these methods can be automatically found by testing.
3, write a suite () method, which uses reflection to dynamically create a method that contains all of the testXxxx test suite:
public static Test suite () {
return new TestSuite (SimpleTest.class);
}
4, write a main () method to run the text mode device to facilitate the operation of the test:
public static void main (String args []) {
junit.textui.TestRunner.run (suite ());
}
}
5, run the test:
Run in text mode:
java junitfaq.SimpleTest
Through the test results are:
.
Time: 0
OK (1 tests)
Time said the test on the number of small points, and if testing shows OK.Otherwise, the small point behind the marked F, indicates that the test failed.
Each of the test results should be OK, so in order to explain the test is successful, if unsuccessful the information will immediately follow the prompts revised.
JUnit test report if not successful, it will distinguish between failures (failures) and mistakes (errors).Failure is the code in your method fails due to assert; and the error is caused by abnormal code, such as ArrayIndexOutOfBoundsException.
Graphically run:
java junit.swingui.TestRunner junitfaq.SimpleTest
The test results through the graphical interface of the green bar in part.
These are the most simple test sample, the actual test, we test the function of a class is often necessary to perform some common operations, after the completion of the destruction of the resources needed (such as network connections, database connections, close open filesetc.), TestCase class provides us with a setUp method and tearDown methods, setUp method to test your content in the preparation of the TestCase subclass method before each testXxxx will run, and tearDown methods of content after the end of each method will be executed testXxxx.The shared initialization code only, but also eliminates the potential between each test code interaction.
JUnit best practices
Martin Fowler said: "When you try to print out some information or debugging an expression, write some test code to replace those traditional methods." At first, you will find that you always want to create some new Fixture, and the testprogramming seems to slow you down.Soon after, however, you will find that you repeat the same Fixture, and the new test is usually only involves adding a new test method.
You may write a lot of test code, but you soon find that you envisage only a small part of the test is really useful.You need to test is the test that will fail, that you think will not fail those tests, or do you think they should fail the test of success.
As we mentioned earlier testing is a process without interruption.Once you have a test, you should ensure that their work has been to test your work by adding new code.Do not run every few days or the last test day, you should run this test code.This investment is very small, but it can work to ensure that you get reliable code.Reduce your rework rate, you will have more time to write working code.
Do not think that pressure, do not write test code.Instead write test code will gradually reduce your stress, should be tested by writing code, you have the exact behavior of the class's understanding.You will be faster to write code to work efficiently.
Here are some specific skills in writing test code or good practices:
1. Do not use the TestCase constructor initializes Fixture, but rather use the setUp () and tearDown () method.
2. Do not rely on or assume that the order of test runs, because the JUnit test method using Vector saved.So different platforms will be in a different order, remove from the Vector test methods.
3. To avoid the side effects of the preparation of a TestCase.For example: If subsequent tests depends on the specific transaction data, do not submit transaction data.Will simply roll on it.
4. When inheriting a test class, remember to call the superclass setUp () and tearDown () method.
5. Will test the code and working code together, while simultaneously compile and update.(Using the junit Ant had to support the task.)
6. Test classes and test methods should have a consistent naming scheme.If the working class name with the test to form the test class name.
7. To ensure that the test is independent of time, do not rely on outdated data used for testing.Resulted in the subsequent maintenance of the process is difficult to reproduce the test.
8. If you are writing software for the international market, the preparation of the test to consider when international factors.Native Locale not only for testing.
9. As much as possible to provide the use of JUnit to assert / fail method and the method of exception handling can make the code more concise.
10. The test to be as small as possible, the implementation of speed.
Combination of JUnit and ant
cherami Links
ant provides two target: junit and junitreport
Run all test cases, and generate html-formatted report
To do the following:
1. ANT_HOMElib directory on the junit.jar
2. Modify build.xml, add the following:
--------------------------------------------------------- One or more tests failed, check the report for detail ... ---------------------------------------------------------
Run this target, ant will run each TestCase
Directory in the report there is a lot of TEST *. xml and some pages
Open the report directory index.html you can see a very intuitive test run reports at a glance.