Unit testing tool JUnit 4
JUnit best practices
You intend to put the code on unit testing, what places? Put it and test code mixed together, apparently, will into confusion, because unit test code is not appear in the final product. We recommend that you separately for the unit testing code and test code to create a separate directory, and to ensure the test code and test code using the same package name. This is to ensure the separation of the code, but also guarantees the search convenience. General recommendation to test the source packages called testsrc now we have a JUnit best practices: unit testing code and test code using the same package, different directory.
JUnit 4's new features
With Java 5 Notes, JUnit 4 and lighter than before (the order), but also more flexible. JUnit 4 to abandon a strict naming convention and inheritance level, turning a number of exciting new features. The following is a report on new features in JUnit 4 Express list:
1. Parameter test
2. Abnormal test
3. Overtime test
4. Flexible firmware
5. Ignore the easy way to test
6. For testing the logic of the new method of grouping
JUnit4 experience new features
First of all, we were required to construct a test-class
package jtest;
public class Calculator (
private static int result; / / static variables used to store the results
public void add (int n) (
result = result + n;
)
public void substract (int n) (
result = result - n; / / Bug: should be the correct result = result-n
)
public void multiply (int n) (
) / / This method has not yet written
public void divide (int n) (
result = result / n;
)
public void square (int n) (
result = n * n;
)
public void squareRoot (int n) (
for (;;)
; / / Bug: Die cycle
)
public void clear () (/ / Clear results
result = 0;
)
public int getResult () (
return result;
)
)
Experience 1: Do not need before the test time is less complex, some are so easy
@ Test
public void testAdd () (
calculator.add (2);
calculator.add (3);
assertEquals (5, calculator.getResult ());
)
This will add the completion of a complete method of testing and test this prefix is not a must, if you add there is no difference between
note:
1. The test method must be modified to use Notes org.junit.Test.
2. Testing methods must be used public void modified, but should not contain any parameters
Remember: Your unit test code is not used to prove you are right, but in order to prove that you do not mistake. Thus the scope of unit testing should be comprehensive, such as the boundary value, the normal value, the error is worth testing;
Code problems that may occur to the full prediction, which is the needs analysis, detailed design aspect to be considered.
If your test fails, there will be no progress in the green section
JUnit test failure will be divided into two types: failure and error. Failure in general by the unit testing method used to determine that the failure cause, it said at the test point problem found;
The error is caused by abnormal code, which is outside the purpose of testing found that it may generate the test code itself error (test code is code, the same can not guarantee that there is no defect),
Probably also are being tested code in a hidden bug
Experience 2 Fixture
What is a Fixture? It refers to the implementation of one or more test methods required a series of public resources or data, such as test environment, test data and so on.
In the preparation of unit testing process, you'll find at most of the testing methods prior to conducting the test are really necessary to do many bedding - for the design and preparation Fixture busy.
These pave the way to occupy the process of code testing, more often than not really code much, but this ratio as the test complexity of the incremental increase.
When multiple testing methods are necessary to pave the way to do the same, the duplicate code of "bad taste" in the test code in open diffuse. This is a "bad taste" will taint your code, but also because of negligence caused the error, you should use some means to eradicate it.
JUnit provides a set of specialized public Fixture methods, the same test all types of test methods can share it to initialize Fixture and write-off Fixture.
JUnit test methods and the preparation of the same, public Fixture settings is also very simple, you only need to:
1. The use of annotation org, junit.Before modified method for the initialization Fixture.
2. Org.junit.After the use of annotations for the write-off Fixture modified method.
3. To ensure that these two methods are the use of public void modified, but should not contain any parameters.
Follow the above three principles, the preparation of the code are generally like this:
/ / Initialization method Fixture
@ Before
public void init () (... ...)
/ / Write-off Fixture Ways
@ After
public void destroy () (... ...)
In this way, at each before the execution of a test, JUnit will guarantee init method to initialize a test environment in advance, and when the implementation of this test after, JUnit will call the destroy method of write-off test environment.
Note that each test method will trigger the implementation of public Fixture settings, meaning that the use of Notes Before or After modified public Fixture level set method is the Ways.
This will ensure that all the independent non-interfering between the test, other test code changes in order to avoid a test environment or test data affect the accuracy of other test code.
However, this approach Fixture settings or attracted criticism because of its low efficiency, especially in the setting Fixture very time-consuming cases (such as set up the database link).
Change will not happen but also for the test environment or test data is that there will not affect the test results of the implementation, it is not necessary for each test method to reset a Fixture.
JUnit 4 in the introduction of the category level of Fixture setting methods, the preparation of specification as follows:
1. The use of annotation org, junit.BeforeClass modified method for the initialization Fixture.
2. Org.junit.AfterClass the use of annotations for the write-off Fixture modified method.
3. To ensure that these two methods are the use of public static void modified, but should not contain any parameters.
Fixture type of level only at testing all types of testing methods to initialize before the execution of the implementation and testing methods to test at all after the implementation of write-off method. Template code is as follows:
/ / Class Level Fixture initialization method
@ BeforeClass
public static void dbInit () (... ...)
/ / Class Level Fixture write-off method
@ AfterClass
public static void dbClose () (... ...)
Experience three: abnormal test
Notes Medium org.junit.Test have two very useful parameters: expected and timeout. Parameters expected out expectations on behalf of test methods specified abnormal, if the test did not run out this anomaly,
JUnit will then consider the test did not pass. This authentication method being tested at the wrong circumstances it will be thrown out of the anomaly is scheduled to provide a convenience.
For example, divide Ways to 0 if the parameters will be thrown ArithmeticException abnormal test whether it will divide the exception of 0 out designated abnormal unit testing methods generally are as follows:
@ Test (expected = ArithmeticException.class)
public void divide () (
... ...
)
Experience four: Time to test
Notes org.junit.Test Another parameter timeout, specified by the test method is allowed to run, the longest should be the number, if the test run for more than a specified number of milliseconds,
Consider the JUnit test failed. This parameter for the performance test must have help.
@ Test (timeout = 1000)
public void testSubstract () (
... ...
)
Experience Friday: ignore test methods
JUnit to provide comments for the time being ignored org.junit.Ignore a testing method, because sometimes because of limited test environment, and can not guarantee that each test method can function correctly.
If you do not have any implementation or lack of certain resources
@ Ignore ( "Multiply () Not yet implemented")
public void testMultiply () (
)
But must be careful. Notes org.junit.Ignore can only be used to temporarily ignore the test, if necessary Forever ignore these tests, must be tested to confirm the code of these testing methods are no longer required in order to avoid neglect the necessary test points.
Experience six: Test Run Explorer
Also a new concept emerged - Test running browser, JUnit tests for all methods are responsible for the implementation of it. JUnit for unit testing provides a default test run, but did not restrict JUnit you must use the default browser to run.
Instead, you can not only run their own customized browser (all browser are inherited from the running org.junit.runner.Runner), but also a test for each category of designated use of a specific browser to run.
Specified method is also very simple, use the Notes category on the test org.junit.runner.RunWith explicit statement to be used to run the browser:
@ RunWith (CustomTestRunner.class)
public class CalculatorTest (
... ...
)
It is obvious that if the tests are no explicit statement of the use of which device a test run, JUnit will be activated in the default test run to perform the test category (such as the above-mentioned unit testing code).
Under normal circumstances, the default test run can cope with the overwhelming majority of the unit testing requirements; when using JUnit to provide some advanced features (such as the forthcoming introduction of both features) or for the special needs of custom JUnit test, the
Explicit statement of the test run a browser on the essential.
Experience seven: test suite
In actual projects, with the launching of project, unit testing more and more categories will be many, but until now we have only one individual running the test class, this practice in the actual project is not feasible.
In order to solve this problem, JUnit provides a batch run test-class method, called the test suite. In this way, each will need to verify the correctness of system functions, only the implementation of one or some test suite can be had.
The wording of the test suite is very easy, you only need to follow the following rules:
Create an empty category as the entrance test suite.
Notes org.junit.runner.RunWith use and modification of the air org.junit.runners.Suite.SuiteClasses category.
Will be imported as a parameter org.junit.runners.Suite Notes RunWith, in order to prompt the use of JUnit for such kits to perform operation.
Add this test will be required to test suite composed of an array type as a comment SuiteClasses parameters.
Ensure that this type of use of public space modification, and the existence of any non-public constructor parameters.
@ RunWith (Suite.class)
@ Suite.SuiteClasses ((
CalculatorTest.class,
SquareTest.class
))
public class AllCalculatorTests (
)
Example code on, we will test mentioned above category CalculatorTest Add a test suite AllCalculatorTests, in Eclipse to run test suite,
Can see the test-class is called CalculatorTest implemented. Test suite can contain not only test the basic category, but can contain other test suites, this can easily manage different hierarchical module unit testing code.
However, you must test suite to ensure that the cycle contains no relations, otherwise endless cycle will appear in front of you ... ....
Experience eight: Parametric test
Parametric tests to prepare a little bit of trouble (of course this is relative to other characteristics JUnit):
To prepare for the use of parametric tests to test the operation of special types of specified device org.junit.runners.Parameterized.
To test some type of statement variables, separately for the storage of expectations and test data used.
To test the use of annotation-type declaration of a modified org.junit.runners.Parameterized.Parameters, java.util.Collection return value of the public static method, and in this method to initialize all required test parameters right.
To test the type of statement with a parameter public constructor and at one of the second aspect of the statement of some variable assignment.
The preparation of test methods, the use of the definition of the variable as a parameter for testing.
@ RunWith (Parameterized.class)
public class SquareTest (
private static Calculator calculator = new Calculator ();
private int param;
private int result;
@ Parameters
public static Collection <Object[]> data () (
return Arrays.asList (new Object [] [] (
(2, 4),
(0, 0),
(-3, 9),
));
)
/ / Constructor to initialize variables
public SquareTest (int param, int result) (
this.param = param;
this.result = result;
)
@ Test
public void square () (
calculator.square (param);
assertEquals (result, calculator.getResult ());
)
)








Responses to “Unit testing tool JUnit 4”