Experience sharing with JUnit test framework

Source: Internet
Author: User

 

1. Learn the use of the JUnit framework
You can learn from the following two examples.
A, JUnit use Method Example 1
1) bring JUnit into the current project library
Create a new Java Project-cooljunit, open the Project Cooljunit's property page, select the Java Build Path Sub-option, click the "Add Library ..." button, and in the "Add Library" dialog box that pops up Select JUnit in the next page and select version JUnit 4 and click the "Finish" button. This introduces JUnit into the current project library.
2) new unit Test Code Catalog
Unit test code does not appear in the final software PRODUCT, so it is a good idea to create a separate directory for the unit test code and the code being tested, and to ensure that the test code and the code being tested use the same package name. This ensures the separation of the code, while also ensuring the convenience of the search. In accordance with this principle, add a new directory testsrc in the project Cooljunit root directory and include it in the project source code directory.
3) Adding classes in the project
Add Class Samplecaculator, with two methods in the class that calculate addition and subtraction, respectively. Compile the code.
public class Samplecalculator {
Calculates the sum of two integers
public int Add (int augend, int addend) {
return augend + addend;
}
Calculate the difference between two integers
public int subtration (int minuend, int subtrahend) {
return minuend-subtrahend;
}
}
4) write Unit test code
Add test cases for class Samplecalculator. At the Explorer Samplecalculator.java file, right-click the new> selected JUnit test case (see Figure 4), Source Foler Select Testsrc Directory, click Next, select the method to test, Here the Add and Subtration methods are selected, the last point finish.
JUnit automatically generates the test class samplecalculatortest, modifying the code (below).
Where assertequals assertions are used to test whether the expected target and actual results are equal.
Assertequals ([Sting message], expected, actual)
Expected is expected (usually hard-coded), actual is the actual value generated by the code being tested, and the message is an optional one, and if provided, the message will be reported when an error occurs.
If you want to use assertions to compare floating-point numbers (in Java, the number of types is float or double), you need to specify an additional error parameter.
Assertequals ([Sting message], expected, actual, tolerance)
See also textbook and reference books for other assertions. The test method needs to be written according to certain specifications:
1.The test method must use the callout org.junit.Test adornment.
2. the test method must be decorated with public void and cannot have any parameters.
5) View running results
Right-click on the test class and select Run as JUnit test in the pop-up menu. Running results such as, green progress bar prompts us, the test run passed.

B, junit example of how to use 2
1) Adding classes in the project
The functionality of the method WORDFORMAT4DB () implemented in class Worddealutil is described in file annotations.
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;
public class Worddealutil {
/**
* Java object names (capitalize the first letter of each word) according to the
* Database naming habits are formatted
* Formatted data is lowercase and uses an underscore to split a named word
* Example: EmployeeInfo becomes employee_info after formatting
* @param name Java object names
*/
public static string wordformat4db (string name) {
Pattern p = pattern.compile ("[A-z]");
Matcher m = p.matcher (name);
StringBuffer strbuffer = new StringBuffer ();
while (M.find ()) {
Replaces the current matching substring with the specified string.
and adds the replaced substring and the string segment that precedes the last matching substring to a StringBuffer object
M.appendreplacement (Strbuffer, "_" +m.group ());
}
Adds the remaining string to a StringBuffer object after the last matching work
Return M.appendtail (Strbuffer). toString (). toLowerCase ();
}
}
2) write unit test code
Import static org.junit.assert.*;
Import Org.junit.Test;
public class Worddealutiltest {
@Test
public void testwordformat4db () {
String target = "EmployeeInfo";
String result = worddealutil.wordformat4db (target);
Assertequals ("Employee_info", result);
}
}
3) Further refine the test case
The scope of the unit test should be comprehensive, such as the boundary value, normal value, error values test. The test case is further perfected by using the design method of the test case, such as equivalence class partition method and boundary value analysis method. Continue to add some tests for special cases:
TestProcessing when NULL is in progress
@Test public void Wordformat4dbnull () {
String target = null;
String result = worddealutil.wordformat4db (target);
Assertnull (result);
}
To test the processing of an empty string
@Test public void Wordformat4dbempty () {
String target = "";
String result = worddealutil.wordformat4db (target);
Assertequals ("", result);
}
To test the case when the first letter is capitalized
@Test public void Wordformat4dbegin () {
String target = "EmployeeInfo";
String result = worddealutil.wordformat4db (target);
Assertequals ("Employee_info", result);
}
To test the case when the tail letter is capitalized
@Test public void Wordformat4dbend () {
String target = "Employeeinfoa";
String result = worddealutil.wordformat4db (target);
Assertequals ("employee_info_a", result);
}
When you test multiple connected letters in uppercase
@Test public void Wordformat4dbtogether () {
String target = "Employeeainfo";
String result = worddealutil.wordformat4db (target);
Assertequals ("Employee_a_info", result);
}
4) View the results of the analysis run and modify the error code
Run the test again. The JUnit runtime interface prompts us to have two test cases failing the test (see Figure 6), where the result of the initial capitalization is biased against the expected, resulting in a test failure (failure), and when the result of null processing is tested, the exception is thrown directly-the test error. Obviously, the code in the test does not deal with both the initial capitalization and the null, which are modified as follows:
Modified Method Wordformat4db
public static string wordformat4db (string name) {
if (name = = null) {
return null;
}
Pattern p = pattern.compile ("[A-z]");
Matcher m = p.matcher (name);
StringBuffer sb = new StringBuffer ();
while (M.find ()) {
if (M.start ()! = 0)
M.appendreplacement (SB, ("_" +m.group ()). toLowerCase ());
}
Return M.appendtail (SB). ToString (). toLowerCase ();
}
2. Use the JUnit framework to unit test class date and class Dateutil.
Test only the methods that contain the business logic, including:
Class in date.
Isdayvalid (int year, int month, Int. day)
Ismonthvalid (int month)
Isyearvalid (int year)
In the class Dateutil
Isleapyear (int year)
Getdayofyear (date date)

This article was selected from: http://www.spasvo.com/news/html/2014123144207.html

Experience sharing with JUnit test framework

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.