2.2 Junit Test Method Introduction

Junit. Framework is the most important package in junit. It contains all of junit’s core classes, including Assert, TestCase, TestResult, and TestSuite.

2.2.1 Assert class

The Assert class provides a set of assertion methods to write test cases, allowing you to check the expected result value and true return value of the test method, and only failed assertions are logged.

JUnit provides overloadable assertion methods for all primitive types, objects, and arrays. In the assertion method, the order of parameters is expected output first, followed by real values. The number of parameters does not have to be two (expected and true), but you can optionally fill in the first parameter as an error message.

The important methods of the Assert class are shown in Table 2.1 below:

methods describe
 assertNull(java.lang.Object object) Check whether the object is empty
 assertNotNull(java.lang.Object object) Check whether the object is not empty
 assertEquals(long expected, long actual) Check that the values of type long are equal
 assertEquals(double expected, double actual, double delta) Checks whether double values of the specified precision are equal
 assertFalse(boolean condition) Check whether the condition is false
 assertTrue(boolean condition) Check if the condition is true
 assertSame(java.lang.Object expected, java.lang.Object actual) Check whether two object references refer to the same object (that is, whether objects are equal)
 assertNotSame(java.lang.Object unexpected, java.lang.Object actual) Check whether two object references do not refer to uniform objects (that is, objects are unequal)

Table 2.1 main methods of assertions

In the simple test process demonstrated in the previous chapter, we use the assert method to judge whether the results of the four operations of addition, subtraction, multiplication and division are the same as the expected results. If they are the same, it means that the method of addition, subtraction, multiplication and division defined by us is not wrong. If not, the system will prompt us where the expected value conflicts with the actual value, so that we can check for errors.

In addition to the assertion methods described above, Junit4 introduced a new assertion method called assertthat, which takes an optional error message, the true output value of the test, and a Matcher object. Note that the order of its arguments (expected and true) is reversed from the values of the built-in traditional assertion. It can use general, string-dependent, numeric-dependent, and collection-dependent cards. The specific method of use is as follows:

 

(I) General cards

 

1, allOf

The match indicates that if all the following conditions must be true for the test to pass, it is equivalent to “and” (&&).

    assertThat( testedNumber, allOf( greaterThan(8), lessThan(16) ) );

2, anyOf

Clause indicated that if the rest of the all the conditions as long as there is a set up the tests pass, the equivalent of “or” (| |)

    assertThat( testedNumber, anyOf( greaterThan(16), lessThan(8) ) );

3, anything

The tie character says it’s always true no matter what the condition is, right

    assertThat( testedNumber, anything() );

4, is

The matching character indicates that if the object to be tested is equal to the object given later, the test passes

   assertThat( testedString, is( “developerWorks” ) );

5, the not

If the object to be tested is not equal to the object given later, the test passes

    assertThat( testedString, not( “developerWorks” ) );

 

(2) String related cards

 

1, containsString

The matching character indicates that the test passes if the testedString testedString contains the substring “developerWorks”

     assertThat( testedString, containsString( “developerWorks” ) );

2, endsWith

The matching character indicates that the test passes if the testedString testedString ends in a substring “developerWorks”

     assertThat( testedString, endsWith( “developerWorks” ) );

3, startsWith

The matching character indicates that the test passes if the testedString testedString starts with the substring “developerWorks”

     assertThat( testedString, startsWith( “developerWorks” ) );

4, equalTo

The tick indicates that the test passes if the testedValue of the test is equalTo the expectedValue, equalTo can test between the values of the string

Equals between objects, equivalent to the equals method of objects

     assertThat( testedValue, equalTo( expectedValue ) );

5, equalToIgnoringCase

The matching character indicates that the test passes if the testedString testedString equals “developerWorks” regardless of case

     assertThat( testedString, equalToIgnoringCase( “developerWorks” ) );

6, equalToIgnoringWhiteSpace

The matching character indicates that the test passes if the string testedString is equal to “developerWorks” without any Spaces at the beginning or end. Note that Spaces in the string cannot be ignored

     assertThat( testedString, equalToIgnoringWhiteSpace( “developerWorks” ) );

 

(iii) value related cards

 

1, closeTo

The tick indicates that the test passes if the tested float testedDouble is in the range of 20.0±0.5

AssertThat (testedDouble, closeTo(20.0, 0.5));

2, greaterThan

The match indicates that the test passes if the tested value testedNumber is greater than 16.0

AssertThat (testedNumber, greaterThan (16.0));

3, lessThan

The match indicates that the test passes if the tested value testedNumber is less than 16.0

AssertThat (testedNumber, lessThan (16.0));

4, greaterThanOrEqualTo

The match indicates that the test passes if the tested value testedNumber is greater than or equal to 16.0

AssertThat (testedNumber, greaterThanOrEqualTo (16.0));

5, lessThanOrEqualTo

The match indicates that the test passes if testedNumber is less than or equal to 16.0

AssertThat (testedNumber, lessThanOrEqualTo (16.0));

 

(iv) Collection related cards

 

1, hasEntry

If the test Map object mapObject contains an Entry with a key value of “Value”, the test passes

     assertThat( mapObject, hasEntry( “key”, “value” ) );

2, hasItem

The match indicates that the test passes if the iterableObject tested contains the element “Element” item

     assertThat( iterableObject, hasItem ( “element” ) );

3, hasKey

If the test Map object mapObject contains key, the test passes

     assertThat( mapObject, hasKey ( “key” ) );

4, hasValue

If the test Map object mapObject contains the element value value, the test passes

     assertThat( mapObject, hasValue ( “key” ) );

AssertThat has many advantages. 1. It can replace many assertion statements, including assertEquals. 2. AssertThat uses The Matcher matching character of Hamcrest. Users can specify some conditions they want to set accurately by matching criteria specified by matching character, which has strong readability and is more flexible in use. 3. AssertThat no longer uses the more difficult syntax pattern of ‘subjection’ as assertEquals(e.g. Instead, assertThat uses a readable grammatical pattern similar to “subject-verb-object” (e.g. AssertThat (x,is(3));) , making the code more intuitive and easy to read; AssertThat method can combine these Matcher matching characters and use them flexibly to achieve more purposes. 5. AssertThat method error messages are more understandable, readable and descriptive; 6. Developers can implement the Matcher interface to customize their own matching characters. When developers find that some of their test code is repeatedly used in different tests, users can customize the match characters and bind the code into an assertion statement, thus reducing the number of duplicate code and making it easier to read.

2.2.2 the TestCase class

TestCase classes are central to the JUnit framework. You can find TestCase in the junit.framework package. A common confusion among JUnit developers is the relationship between test cases and TestCase classes. The term “test case” usually refers to a single test, coded to verify a particular behavior. Collect multiple test cases into a class that is a subclass of TestCase, and each TestCase is implemented as a method in the TestCase class.

While writing tests, you need to create a subclass of “TestCase” and implement each TestCase as a method of that new class; But at run time, each test case is run as an instance of a TestClass subclass. In object-oriented terms, each TestCase is an object of TestCase.

TestCase defines a fixed format for running multiple tests, and the important methods are shown in Table 2.2:

methods describe
 int countTestCases() Counts test cases executed by run(TestResult Result)
 TestResult createResult() Create a default TestResult object
 String getName() Gets the name of TestCase
 TestResult run() A convenient way to run this test, collecting the results produced by the TestResult object
 void run(TestResult result) Run the test case in TestResult and collect the results
 void setName(String name) Set the name of TestCase
 void setUp() Create fixed Settings, such as opening a network connection
 void tearDown() Remove fixed Settings, for example, to close a network connection
 String toString() Returns a string representation of the test case

Table 2.2 Main methods of TestCase

 

2.2.3 TestResult class

The TestResult class collects the results of all test cases executed and is an example of the collection parameter layer. The TestResult class can distinguish between failures and errors. Failures are predictable and can be examined by assumptions, while errors are unpredictable problems.

Some important methods of the TestResult class are shown in Table 2.3:

methods describe
void addError(Test test, Throwable t) Add an error to the error list
void addFailure(Test test, AssertionFailedError t) Adds a failure to the failure list
 void endTest(Test test) Displays the result of the test being compiled
 int errorCount() Gets the number of detected errors
 Enumeration errors() Returns details of the associated error
 int failureCount() Gets the number of detected failures
 void run(TestCase test) Run the TestCase
 int int runCount() Get the number of tests run
 void startTest(Test test) Declaration testing is about to begin
 void stop() Declare that tests must stop

Table 2.3 TestResult methods

2.2.4 TestSuite class

The TestSuite class is Junit’s TestSuite and runs many test cases. Some important methods of the TestSuite class are shown in Table 2.4:

methods describe
 void addTest(Test test) Add tests to your test suite
void addTestSuite(Class<? extends TestCase> testClass) Add tests from a given class to a test suite
 int countTestCases() Count the test cases that this test is about to run
 String getName() Returns the name of
 void run(TestResult result) Run the test case in TestResult and collect the results
 void setName(String name) Set the name
 Test testAt(int index) Returns tests in the given directory
 int testCount() Returns the number of tests in the test suite
static Test warning(String message) Return tests that will fail and log warnings

Table 2.4 Main methods of TestSuite

2.2.5 Sample assertion code

Let’s first demonstrate assertions in action. We use a test case to show the basic assertion method:

import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.Test; Public class AssertionsTest {// Test is null @test public void testAssertNull() {String STR = null; assertNull(str); } @test public void testAssertNotNull() {String STR = "Hello Java!!" ; assertNotNull(str); } @test public void testAssertEqualsLong() {Long long1 = 2; long long2 = 2; assertEquals(long1, long2); } @test public void testAssertEqualsDouble() {// Test case is successFull as double1 and Double 2 // Differ by 0.001 which is less than our specified delta double double1 = 1.236; Double double2 = 1.237; Double delta = 0.002; assertEquals(double1, double2, delta); } @test public void testAssertTrue() {List<String> List = new ArrayList<String>(); assertTrue(list.isEmpty()); } @test public void testAssertFalse() {List<String> List = new ArrayList<String>(); list.add("hello"); assertFalse(list.isEmpty()); @test public void testAssertSame() {String str1 = "Hello world!!" ; String str2 = "hello world!!" ; assertSame(str2, str1); @test public void testAssertNotSame() {String str1 = "Hello world!!" ; String str3 = "hello Java!!" ; assertNotSame(str1, str3); }}Copy the code

To demonstrate the use of assertThat, create a new Java test class:

 

public class A { public int add(int a, int b) { return a + b; } public double div(double a, double b) { return a / b; } public String getName(String name) { return name; } public List<String> getList(String item) { List<String> l = new ArrayList<String>(); l.add(item); return l; } public Map<String, String> getMap(String key, String value) { Map<String, String> m = new HashMap<String, String>(); m.put(key, value); return m; }}Copy the code

Let’s create a new test case for this class. The code is as follows:

 

import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import java.util.List; import java.util.Map; import org.junit.Test; Public class ATest {@test public void testAdd() {int s = new C().add(1, 1); AssertThat (s, allOf(greaterThan(1), lessThan(3)))); AssertThat (s, anyOf(greaterThan(1), lessThan(1)))); //anything: The test passes assertThat(s, anything()) regardless of the condition; //is: test through assertThat(s, is(2)) when the value of the variable is equal to the specified value; // Not: assertThat(s, not(1)) is tested when the value of the variable is not equal to the specified value; // double d = new C().div(10, 3); //closeTo: Float variable values within 3.0±0.5, test through assertThat(d, closeTo(3.0, 0.5)); //greaterThan: assertThat(d, greaterThan(3.0)) is tested when the value of the variable is greaterThan the specified value; LessThan: assertThat(d, lessThan(3.5)) is tested when the value of the variable is lessThan the specified value; //greaterThanOrEuqalTo: assertThat(d, greaterThanOrEqualTo(3.3)) is tested when the value of the variable is greaterThanOrEqualTo the specified value; //lessThanOrEqualTo: assertThat(d, lessThanOrEqualTo(3.4)) tests when the value of the variable is lessThanOrEqualTo the specified value; String n = new C().getName("Magci"); AssertThat (n, containsString("ci"))); //startsWith: assertThat(n, startsWith("Ma")) is tested when the string variable begins with the specified string; //endsWith: the test passes assertThat(n, endsWith(" I ")) when the string variable endsWith the specified string; //euqalTo: string variable is equalTo the specified string when tested through assertThat(n, equalTo("Magci")); //equalToIgnoringCase: The test passes assertThat(n, equalToIgnoringCase("magci")) when the string variable equals the specified string without case; / / equalToIgnoringWhiteSpace: string variable in the case of ignoring end any Spaces is equal to the specified string when test pass assertThat (n, equalToIgnoringWhiteSpace (" Magci ")); List<String> l = new C().getList("Magci"); AssertThat (l, hasItem("Magci"))); Map<String, String> m = new C().getMap("mgc", "Magci"); AssertThat (m, hasEntry(" MGC ", "Magci"))); AssertThat (m, hasKey(" MGC "))); AssertThat (m, hasValue("Magci"))); }}Copy the code

 

In addition to the naming conventions mentioned earlier, there are several test method specifications. For example, each Test method must be preceded by “@test”, which is a Test method written below the system description. In the previous version of Junit, Test methods needed to inherit TestCase classes, but in Junit4 a new feature called “@test” was added. In addition, each method in the test case must be testable independently, without any dependencies or interference between test methods.

In the structure of the project, it is best to create a new source code directory to store the test code, which can be easily deleted after the test is completed, without interfering with the original project. I encourage you to generalize from the assertion code above.