JUNIT4 New Assertion Syntax Introduction (RPM)

Source: Internet
Author: User
Tags assert readable

1. Introduction
JUNIT4 's new assertion syntax has many advantages and is simple to use, which is no longer a novelty, and can be found in the actual test code has not been widely used, the text, in order to more people to master the use.
2. Assertthat Basic Grammar
Hamcrest is a test aid tool that provides a common set of matching characters Matcher and uses the rules defined by these matches flexibly, so that programmers can express their test ideas more accurately and specify the test conditions they want to set.
JUNIT4 combines hamcrest to provide a new assertion statement-assertthat, just a assertthat statement, combined with the match provided by Hamcrest, can express all the test ideas.
The basic syntax for Assertthat is as follows:

Assertthat (T actual, Matcher Matcher)
Assertthat (String reason, T actual, Matcher Matcher)

Actual is the next value you want to verify;
Matcher is a declaration of the value expected by the preceding variable, expressed using a hamcrest match, if the actual value matches the expected values expressed by Matcher, the assertion succeeds, or the assertion fails.
Reason is the information that is displayed when a custom assertion fails.
A simple example:
If the test string testedstring contains a substring of "Taobao", the assertion succeeds
Assertthat (testedstring, containsstring ("Taobao"));
3. Assertthat Advantages and Unity

Only one assertthat statement can replace the old other statements (such as assertequals,assertnotsame,assertfalse,asserttrue,assertnotnull,assertnull, etc.) Make assertions simple, code-style uniform, and enhance the readability and maintainability of your test code.
 Grammatically intuitive and understandable

Assertthat is no longer like assertequals, using the more difficult to understand the "host-guest" grammatical pattern (such as: Assertequals (3, X); Instead, Assertthat uses a "subject-verb"-readable syntax pattern (such as: Assertthat (X,is (3)), which makes the code more intuitive, readable and consistent with human thinking habits.
 Error messages are more descriptive

Old assertion syntax if the assertion fails, no additional prompts are available by default, such as
Asserttrue (Testedstring.indexof ("Taobao") >-1);
If the assertion fails, only unwanted error messages, such as Java.lang.AssertionError, will be thrown, and no more prompts will be available.
The new assertion syntax automatically provides some readable descriptive information by default, such as
Assertthat (testedstring, containsstring ("Taobao"));
If the assertion fails, the error message that is thrown is as follows:
Java.lang.AssertionError:
Expected:a string containing "Taobao"
Got: "Taoba"

 Use with matcher matching is more flexible and powerful

The

Matcher provides feature-rich matching characters that can be used to express test ideas with more flexibility and accuracy assertthat with these matches.
//Verify that the string s contains a
//old assertion in the middle of a substring "taobao" or "QA", which is not intuitive, requires parsing code logic to understand the validation intent
Asserttrue (S.indexof ("Taobao") >-1| | S.indexof ("QA") >-1);
//New assertion, intuitive, accurate expression of test ideas
Assertthat (s,anyof (containsstring ("Taobao"), Containsstring ("QA"));
// Anyof satisfies one of the conditions, the containsstring contains a string that is set up
4. Assertthat use
in order to exert the power of assetthat, it must be used in conjunction with Hamcrest, and JUNIT4 itself contains some Hamcrest match Matcher, but only a limited number. It is therefore recommended that you add the Hamcrest package to the project.
Add hamcrest dependencies to the POM.
<dependency>
<groupid>org.hamcrest</groupid>
<artifactid>hamcrest-all</ Artifactid>
<version>1.1</version>
</dependency>
Importing packages in test classes
Import static org.junit.assert.*;
Import static org.hamcrest.matchers.*;
Learning by example is one of the most effective ways to learn, and the following examples show how to use Assertthat, in more detail, refer to the hamcrest documentation. Character-related matching characters


The/**equalto match asserts that the measured testedvalue equals Expectedvalue,
* Equalto can assert equality between values, between strings and objects, equivalent to the Equals method of object
*/
Assertthat (Testedvalue, Equalto (Expectedvalue));

The/**equaltoignoringcase match asserts that the string testedstring is being measured
* Equal to expectedstring if case is ignored
*/
Assertthat (testedstring, Equaltoignoringcase (expectedstring));

The/**equaltoignoringwhitespace match asserts that the string testedstring is being measured
* is equal to expectedstring in the case of ignoring any spaces at the ends of the tail.
* Note: The spaces in the string cannot be ignored
*/
Assertthat (testedstring, Equaltoignoringwhitespace (expectedstring);

The/**containsstring match asserts that the string testedstring that is being measured contains substrings substring**/
Assertthat (testedstring, containsstring (subString));

The/**endswith match asserts that the string testedstring being measured ends with a substring of suffix * *
Assertthat (testedstring, endsWith (suffix));

The/**startswith match asserts that the string testedstring being measured starts with a substring prefix/
Assertthat (testedstring, startswith (prefix)); Generic match character


The/**nullvalue () match asserts that the value of the object being measured is null*/
Assertthat (Object,nullvalue ());

/**notnullvalue () match asserts that the value of the object being measured is not null*/
Assertthat (Object,notnullvalue ());

The/**is match asserts that the object being measured is equal to the following given matching expression * *.
Assertthat (Testedstring, is (Equalto (expectedvalue));

/**is is one of the abbreviations for the Equalto, the abbreviation for IS (x), the assertion that testedvalue equals expectedvalue*/
Assertthat (Testedvalue, is (Expectedvalue));

/**is, shorthand for the application of the second, is (instanceof (Someclass.class)),
* Assertion Testedobject as an instance of Cheddar
*/
Assertthat (Testedobject, is (Cheddar.class));

The/**not and is matches are just the opposite, asserting that the object being measured is not equal to the object*/given later
Assertthat (testedstring, not (expectedstring));

The/**allof match assertion conforms to all conditions, equivalent to "and" (&&) * *
Assertthat (Testednumber, AllOf (GreaterThan (8), LessThan (16)));

The/**anyof match assertion conforms to one of the conditions, equivalent to "or" (| | )*/
Assertthat (Testednumber, anyof (GreaterThan), LessThan (8)); numeric Correlation matching characters


The/**closeto match asserts that the number of floating-point numbers being measured testeddouble within the 20.0¡à0.5 range */
Assertthat (testeddouble, Closeto (20.0, 0.5));

The/**greaterthan match asserts that the measured value testednumber is greater than 16.0*/
Assertthat (Testednumber, GreaterThan (16.0));

/** LessThan Match asserts that the measured value testednumber is less than 16.0*/
Assertthat (Testednumber, LessThan (16.0));

The/** Greaterthanorequalto match asserts that the value being measured is testednumber greater than or equal to 16.0*/
Assertthat (Testednumber, Greaterthanorequalto (16.0));

The/** Lessthanorequalto match asserts that the testednumber being measured is less than or equal to 16.0*/
Assertthat (Testednumber, Lessthanorequalto (16.0)); Collection-related matching characters


The/**hasentry identifier asserts that the Map object MapObject contains a entry item with a key value of "key" corresponding to "value".
Assertthat (MapObject, Hasentry ("Key", "value"));

The/**hasitem match indicates that the measured iteration object Iterableobject contains element elements and the test is passed.
Assertthat (Iterableobject, Hasitem (Element));

/** Haskey Identifier asserts that the Map object MapObject contains the key value "key" * *
Assertthat (MapObject, Haskey ("key"));

The/** HasValue match asserts that the map object being measured MapObject contains element values value*/
Assertthat (MapObject, HasValue (value));

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.