Writing Test code is certainly the biggest headache for developers. JUnit is a very powerful unit test package. It can test a single/multiple methods of one/more classes, and combine different testcase into testsuit to automate testing tasks.
This article briefly introduces how to use JUnit in eclipse to create a testcase to test a simple class.
Let's write a simple class to be tested as follows:
Package jexi. test;
Public class simple {
Private int N;
Public simple (int n ){
This. n = N;
}
// Returns the absolute value:
Public int Foo (){
Return n> 0? N: (-N );
}
}
The Foo () method returns the absolute value. Next, we will use JUnit to perform a comprehensive test on the Foo () method.
First, create a Java project in eclipse and include plugins/org. junit_3.8.1/JUnit. jar in:
Then write simple. Java and create a JUnit test case for it:
In the displayed dialog box, enter the name of the test class: simpletest, and check setup ():
Compile the test code:
Package jexi. test;
Import JUnit. Framework. testcase;
Public class simpletest extends testcase {
Private simple S1, S2;
Protected void setup () throws exception {
Super. Setup ();
S1 = new simple (10 );
S2 = new simple (-7 );
}
Public void testfoo (){
Asserttrue (s1.foo () = 10 );
Asserttrue (s2.foo () = 7 );
}
}
The setup () method constructs the initialization environment. We create two simple instances in setup. testfoo () is the test method used to test Foo, it is always composed of the test + method name, and then tested in the Test method: s1.foo () = 10. If the returned value is equal to the expected result 10, asserttrue () is executed successfully, now we can run-> Run... -> JUnit test. The test result is displayed on the left:
If we change the simple Foo () method:
Public int Foo (){
Return N;
}
Run JUnit test again. Now asserttrue (s2.foo () = 7); the test result is incorrect. Which row of results will be reported by JUnit is incorrect:
Double-click to quickly locate the method call that fails the test.
Summary:
JUnit is powerful and reliable in terms of code quality. The well-designed testcase can be used repeatedly. If a class is changed in the future, you only need to run testcase once to know whether the change has any impact on the client. Several testcase can also be combined into testsuit and combined with ant to automate the compilation, testing, and running of the entire process. You only need to check the test results to know which code has gone wrong.