JUnit is a Java test framework for development source code for writing and running repeatable tests. He is an instance for unit test framework system xUnit (for Java language). It includes the following features:
1. Assert the results of the expected result (Assertion)
2, test tools for sharing joint test data
3, test kit for easy organization and run test
4, graphics and text test runners
JUnit was originally written by Erich Gamma (one of GOFs) and Kent Beck (one of the pioneers of XP and Refactor).
It should be noted that JUnit is generally used to perform unit testing, so it is necessary to understand the internal structure of the test code (ie, a so-called white box test), and the JUnit is highly recommended in XP programming and reconstruction (Refactor). Tools, because in the case of automatic unit testing, it can greatly improve the efficiency of development, but in fact, the test code is also required to spend a lot of time and energy, then use this stuff to the end of the benefits? The author thinks this:
1. For XP programming, requests to write test before writing code, so you can force you to think about the function and logic of code (method) before writing code, otherwise the code written is unstable, then you need to maintain simultaneously Test code and actual code, this workload will greatly increase. Therefore, in XP programming, the basic process is this: concept - "Write test code -" Write code - "test, and write testing and writing code is incremental, write a little test, in the next code If the problem can be discovered to track the cause of the problem, reduce the error correction difficulty of returning errors
2. For refactoring, the benefits and XP programming are similar, because reconstruction is also required to change a little measurement, reduce time consumption caused by regression errors.
3. For non-above two cases, we use Junit to write some appropriate tests when developing, because usually need to write code code, may not use JUnit, if you use JUnit, and Interface (Method) Writing Test Code will reduce future maintenance, such as modifications within the method (this is equivalent to reconstruction). Also because JUnit has an assertion function. If the test result does not tell us that the test is not passed, why, and if you want the previous general practice to write some test code to see its output results, then to determine the results correctly The advantage of using JUnit is whether this result is correct. It is to be done. We only need to see if it tells us whether it is correct, and it will greatly improve efficiency in general.
Getting started with JUnit
Cherami finishing
Install JUnit
Install is very simple, first to the following address to download a newest zip package:
http://download.sourceforge.net/junit/
After downloading, unpack it into your favorite directory, assume that it is junit_home, then add junit.jar under junit_home to your system's ClassPath environment variable, for the IDE environment, for the JUnit that needs to be used to increase In the lib, it sets different IDEs with different settings, not much here.
How to write tests using JUnit?
The simplest example is as follows:
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 that the expected result:
Public void testemptycollection () {
Collection color = new arraylist ();
asserttrue ());
}
Note: The JUnit recommended is to start with TEST as the beginning of the method to be tested, so that these methods can be automatically found and tested.
3. Write a Suite () method, which uses reflex dynamics to create a test kit containing all TestXxxx methods:
Public static test suite () {
Return New TestSuite (SimpleTest.class);
}
4. Write a main () method to run the text runner to run the test:
Public static void main (string args []) {
Junit.textui.teStrunner.run (Suite ());
}
}
5, run test:
Run in text:
Java junitfaq.simpletest
The test results pass are:
.
Time: 0
OK (1 tests)
The dots on the time represents the number of tests, and if the test passes the pass, OK is displayed. Otherwise, the rear side of the dot is marked, indicating that the test failed.
Each test result should be OK, so that the test is successful, if it is not successful, it will be corrected immediately according to the prompt information.
If JUnit reports the test is not successful, it will distinguish between failures and errors. Failure is caused by the failure of the assert method in your code; and the error is caused by the code exception, such as ArrayIndexOutofboundSexception.
Run in a graphical way:
Java junit.swingui.teestrunner junitfaq.simpletest
The test result passes the green strip portion of the graphical interface.
The above is the simplest test sample. In the actual test, we test a class of features often need to perform some common operations. After completion, you need to destroy the resource occupied (such as network connection, database connection, close files) Wait, the TestCase class provides us with the setup method and Teardown method. The content of the setup method will run before testing each Testxxxx method you have written, and the content of the Teardown method will execute after each Testxxx method. . This has a total of initialization code, which eliminates the possible interactions between each test code.
JUnit Best Practice
Martin Fowler said: "When you try to print some information or debug an expression, write some test code to replace those traditional methods." At the beginning, you will find that you always have some new FixTure, and test It seems that your programming speed is slow. Soon, you will find that you reuse the same fixture, and new tests usually only involve adding a new test method.
You may write a lot of test code, but you will soon find that the test you want to think is really useful. The test you need is the test that will fail, that is, those that you think will not fail, or you think that you should fail.
We mentioned earlier testing is a process that does not interrupt. Once you have a test, you have to keep it working properly to verify the new work code you join. Don't run test every few days or in the end, you should run test code every day. This kind of investment is small, but you can make sure you get a reliable work code. Your rework rate is low, you will have more time to write work code. Don't think that the pressure is large, don't write the test code. On the contrary, write test code will gradually alleviate your pressure, and you should have an exact understanding of the behavior of the class by writing test code. You will write an efficient work code faster.
Here are some specific methods or better practices for writing test code:
1. Do not initialize FixTure with the constructor of TestCase, and use the setup () and Teardown () methods.
2. Do not rely or assume the order of test run, because JUnit uses the Vector Save Test Method. So different platforms will take out test methods from the vector in different orders.
3. Avoid writing TestCase with side effects. For example: If the subsequent test depends on some specific transaction data, it is not necessary to submit transaction data. Simple will be able to roll.
4. When inheriting a test class, remember to call the SETUP () and Teardown () method of the parent class.
5. Place the test code and work code together and compile and update synchronously. (Task, which is supported in Ant, support JUnit.)
6. Test class and test methods should have a consistent naming scheme. To form a test class name as before the work class is preceded.
7. Make sure the test is not related to time, do not rely on the use of expired data for testing. It is difficult to reproduce the test during subsequent maintenance.
8. If you write software to the international market, you should consider international factors when preparing tests. Don't test only with the mother tongue Locale.
9. Use JUnit to provide an ASSERT / FAIL method as much as possible, and the code can be more concise.
10. Test should be as small as possible and perform fast.
JUnit and Ant combination
Cherami reposted
ANT provides two Target: Junit and Junitreport
Run all test cases and generate reports in HTML format
The specific operation is as follows:
1. Place junit.jar in the ANT_HOME / LIB directory
2. Modify Build.xml, add the following:
There is a lot of Test * .xml and some web pages in the Report directory.
Open the index.html under the Report directory to see very intuitive test run reports, at a glance.