Simple use and template of Junit

Source: Internet
Author: User

Developers should perform unit tests during the development process and identify bugs as soon as possible. JUNIT provides a good testing mechanism for JAVA developers. The following is a simple JUNIT application instance, which is also a reference JUNIT template for beginners.

Package JUnit. sineat. templet; <br/> Import Java. util. hashtable; <br/> Import JUnit. framework. assert; <br/> Import JUnit. framework. testcase; <br/> Import JUnit. framework. testsuite; </P> <p> public class junitb extends testcase {<br/>/** define the class to be tested and the variables used ********** * *****************/<br/> Public hashtable hasha = NULL; // <br/> Public hashtable hashb = NULL; <br/> /*********************************** * ******************/<br/> Public junitb (string name) {<br/> super (name ); // create a subclass <br/>}< br/>/** use setup to initialize the subclass */<br/> protected void setup () throws exception {<br/> super. setup (); <br/> hasha = new hashtable (); // here <br/>}< br/>/** use teardown to destroy the occupied Resources */<br/> protected void teardown () throws exception {<br/> super. teardown (); <br/> // system. GC (); <br/>}< br/>/** write a test method to assert the expected result **/<br/> Public void testbodystatus () {<br/> // hasha = new hashtable (); // You can also remove setup () teardown () <br/> assertnotnull (hasha ); <br/> // hasha. put ("0", "let's try again"); // version test1.error <br/> asserttrue (hasha. isempty ()); // expected to be empty <br/>}< br/>/** write another test method to assert the expected result **/<br/> Public void testbodysame () {<br/> // hashb = (hashtable) hasha. clone (); // test2.error version <br/> hashb = hasha; // test2. OK version <br/> assert. assertsame (hasha, hashb); <br/>}< br/>/** Suite () method, use reflection to dynamically create a test suite containing all testxxxx Methods **/<br/> Public static testsuite Suite () {<br/> return New testsuite (junitb. class); <br/>}< br/>/***** write a main () run the test ****************/<br/> Public static void main (string ARGs []) {<br/> JUnit. textui. testrunner. run (Suite (); // easy to use as a text runner <br/> // JUnit. swingui. testrunner. run (junitb. class); <br/>}< br/>

The above is a simple test sample of JUNIT, which does not require too much consideration of performance and specifications. However, senior JAVA developers suggest:
1. Do not initialize In the constructor of the test case.
The answer is to reload the setUp () method of the test case for initialization.
2. Do not assume the test execution sequence in the test case.
A good habit is to maintain the independence between tests so that the results they execute in any order are the same.
3. manual intervention should be avoided during testing
Experience 2 is about avoiding relevance in different tests, while experience 3 is about avoiding self-correlation in testing.
4. call setUp () and tearDown () of the parent class in the subclass ()
5. do not specify the path of the data file.
6. Put the tested code and tested code in the same directory
7. Test the correct name
8. Regional and national settings should be considered during writing tests
9. Use automatic Exception Handling of Junit to write concise test code
In fact, it is unnecessary to use try-catch in Junit to catch exceptions. Junit will automatically catch exceptions. Exceptions that are not captured are treated as errors.
10. Make full use of Junit's assert/fail Method
AssertSame () is used to test whether two references point to the same object.
AssertEquals () is used to test whether two objects are equal
11. Ensure that the test code has nothing to do with time
12. Use the document Generator for testing.

 

Experience 1. Do not initialize In the constructor of the test case
When we need to add a test, we need to write a test case of our own, such as sometest. If you like
It is not a good habit to perform initialization in constructors. For example:
Public class sometest extends testcase {
Public sometest (string testname ){
Super (testname );
// Initialization code
}
}
Once an exception occurs in the initialization code, such as illegalstateexception, junit will generate an assertionfailederror,
The error message similar to the following is displayed:
J u n I t. f r a m e w o r k. a s e r t I o n f a I l e d e r o r: c a n o t I n s t a n t I a t e s t c a s e: t e s t 1 a t
J u n I t. f r a m e w o r k. a s e r t. f a I l (a s e r t. j a v a: 1 4 3) a t
J u n I t. f r a m e w o r k. t e S t s u I t e $1. r u n t e S t (t e S t s u I t e. j a v a: 1 7 8) A T
J u n I t. f r a m e w o r k. t e S t c a s e. r u n B A R E (t e S t C A S E. j a v a: 1 2 9) A T
J u n I t. f r a m e w o r k. t e s t r e s u l t $1. p r o t e c t (t e s t r e s u l t. j a v a: 1 0 0) a t
J u n I t. f r a m e w o r k. t e s t r e s u l t. r u n p r o t e c t e d (t e s t r e s u l t. j a v a: 1 1 7) a t
J u n I t. f r a m e w o r k. t e S t r e s u l t. r u n (t e S t r e s u l t. j a v a: 1 0 3) A T
J u n I t. f r a m e w o r k. t e S t c a s e. r u n (t e S t c a s e. j a v a: 1 2 0) A T
J u n I t. f r a m e w o r k. t e s t s u I t e. r u n (t e s t u I t e. j a v a, c o m p I e d c o d e) a t
J u n I t. u I. t e s t r u n e r $1 2. r u n (t e s t r u n e r. j a v a: 4 2 9)
This pile of error information is confusing. We only know that junit cannot instantiate a test case. What is the problem?
Where is the error? I don't know!
So what is a good practice?
The answer is to reload the setup () method of the test case for initialization. When the initialization code in setup () has an exception, we get
Is similar to the following error message:
J a v. l a n g. I l e g a l s t a t e x c e p t I o n: o p s a t B P. d t C. s e t u p (d t C. j a v a: 3 4) A T
J u n I t. f r a m e w o r k. t e S t c a s e. r u n B A R E (t e S t C A S E. j a v a: 1 2 7) A T
J u n I t. f r a m e w o r k. t e s t r e s u l t $1. p r o t e c t (t e s t r e s u l t. j a v a: 1 0 0) a t
J u n I t. f r a m e w o r k. t e s t r e s u l t. r u n p r o t e c t e d (t e s t r e s u l t. j a v a: 1 1 7) a t
J u n I t. f r a m e w o r k. t e s t r e s u l t. r u n (t e s t r e s u l t. j a v a: 1 0 3)
...
Obviously, this is much clearer. We can all know that illegalstateexception is generated in line 34th of dtc. java.

Experience 2. Do not assume the test execution sequence in the test case
We know that a junit test case class can contain multiple tests. Each test is actually a method. In the following example
There are two different tests. Although testdothisfirst () prior to testdothissecond (), we cannot assume that
Testdothisfirst () is executed first.
Public class sometestcase extends testcase {
Public sometestcase (string testname ){
Super (testname );
}
Public void testdothisfirst (){
...
}
Public void testdothissecond (){
}
}
Since junit uses a vector internally to store all the tests, test execution is performed on different operating systems and java virtual machines.
Order is unpredictable.
A good habit is to maintain the independence between tests so that the results they execute in any order are the same. If you really need some tests
We can use addtest to execute in a specific order. For example:
Public static testsuite (){
Suite. addtest (new sometestcase ("testdothisfirst ";));
Suite. addtest (new sometestcase ("testdothissecond ";));
Return suite;
}
In this way, we can ensure that junit executes testdothisfirst () and then testdothissecond ().

Experience 3. manual intervention should be avoided during testing
If manual intervention is required for a test code, there are at least two adverse consequences: one cannot be included in an automatic test, such as a nighttime response.
Test; second, it cannot be executed repeatedly. For example, if the data deletion test cannot be completed, everything will be fine. A better way is to automatically complete the test.
Deleted Data. Experience 2 is about avoiding relevance in different tests, while experience 3 is about avoiding self-correlation in testing.
Experience 4. call setup () and teardown () of the parent class in the subclass ()Let's take a look at the following code:
Public class sometestcase extends anothertestcase {
// A connection to a database
Private database thedatabase;
Public sometestcase (string testname ){
Super (testname );
}
Public void testfeaturex (){
...
}
Public void setup (){
// Clear out the database
Thedatabase. clear ();
}
}
Have you found any errors? Setup () should call super. setup () to ensure that the environment of the parent class defined in anothertestcase is
Started. Of course, this is also an exception, that is, the base class can process arbitrary test data.

Experience 5. do not specify the path of the data file
We often need to read test data from the file system, and look at the following code:
Public void setup (){
Fileinputstream Indium ("c: // testdata // dataset1.dat ");
...
}
In this Code, you need to put the test data file dataset1.dat in c:/testdata. This is a problem.
First, the c disk may have no disk space. The tester has to put the data file in another path;
Second, you may need to perform this test on another operating system, such as linux.
Therefore, a better alternative is
Public void setup (){
Fileinputstream Indium ("dataset1.dat ");
...
}
But in fact this is still not very good, because this requires that the path of the data file and the test execution path must be the same, if several different
In this case, it is difficult to integrate these tests for execution. We have to change the current path frequently.
To solve this problem, we can use class. getresource () or class. getresourceasstream ().
You can put the data file on a relative path of this class.
Data files should be stored in the configuration management system together with the source code.
We need to do a job to copy the data file from the original location-a relative path of the source code to the compiled
Is the relative path of the class file. This is not complicated because the package of the class can be mapped
For linux or windows, the path of the java file is replaced by file. separatorchar in the package.

Experience 6: Put the tested code and tested code in the same directory
When we put the test code and tested code in the same directory, We can compile the test code while compiling the tested code.
Make sure that the two are synchronously updated. In fact, the current common practice is to regard unit testing as a part of building.

Experience 7. Correct naming test

Name the test case testclassundertest. For example, if the tested class is messagelog, the test case is called
Testmessagelog. In this way, the test case corresponds to the tested class one by one, and the method of each test in the test case is
It can be named
Testloggingemptymessage ()
Testloggingnullmessage ()
Testloggingwarningmessage ()
Testloggingerrormessage ()
It is also to clarify what the test is. Correct naming helps readers of the test code understand the purpose of each test.
Experience 8. Regional and national settings should be considered during writing tests
For example, if a test requires a date, the following code is a method for creating a date object.
Date date = DateFormat. getInstance (). parse ("dd/mm/yyyy ");
However, if the machine running the above test code uses different regional country settings, there will be problems. Therefore, we 'd better use another
One method:
Calendar cal = Calendar. getInstance ();
Cal. set (yyyy, mm-1, dd );
Date date = Calendar. getTime ();
Obviously, the second method can adapt to the changes in regional country settings.

Experience 9: use automatic Exception Handling of JUnit to write concise test code
Many beginners of Junit often write code similar to the following.
Public void exampleTest (){
Try {
// Do some test
} Catch (SomeApplicationException e ){
Fail ("Caught SomeApplicationException exception ");
}
}
In fact, it is unnecessary to use try-catch in Junit to catch exceptions. Junit will automatically catch exceptions. For exceptions that are not captured
It is treated as an error. Therefore, the code above is redundant and can be written into the code below, which is much equivalent but concise:
Public void exampleTest () throws SomeApplicationException {
// Do some test
}
Less test code is easier to understand and maintain. It cannot be simplified to test whether an exception can be thrown.

Experience 10. Make full use of JUnit's assert/fail Method
Junit has rich and flexible assert/fail methods. How to use these methods well is also worth noting. For example, the following statement is not good.
Assert (creds = 3 );
It is better to write
AssertEquals ("The number of credentials shocould be 3", 3, creds );
The second method is not only easy to read, but also can provide more information to testers if fail is executed.
Junit also supports the assert method of floating point numbers. The following example shows how to clean up the profits:
AssertEquals ("some message", result, expected, delta );
It should also be noted that:
AssertSame () is used to test whether two references point to the same object.
AssertEquals () is used to test whether two objects are equal

Experience 11. Ensure that the test code has nothing to do with time
Try to avoid expired test data. Such data should be refreshed manually or automatically. Another trick is to use these
The current date of the system is changed before the data operation is completed, and the data recovery date is later. Of course, pay attention to possible side effects when using this technique.

Experience 12: Use document builder for testing documents
Of course we can use a text editor to write unit test documents, but a better way is to use document generators such as JavaDoc
In this way, we do not need to worry about synchronization between implementation and documents. The format of automatically generated documents is incorrect.

 

After reading: unit testing seems to be done by the QA department, but most white-box tests still need to be done by the Develop Department. The tests made by junit are readable, writing a class everywhere to test is not a good habit, including this bad habit.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.