JUNIT4 Unit Test Basics

Source: Internet
Author: User

Introduction

JUnit plays an important role in test-driven development (TDD) as a test framework for the Java language. as We all know, whether to develop large-scale projects or general small projects,

unit testing is critical. Unit Testing provides a great convenience for software to test and maintain. JUnit 4, as the latest version, adds a lot of new features,

with Hamcrest, you can write a lot of flexible tests. starting with JUnit 4, the jar package is placed under the Org.junit package. The code is already hosted on GitHub.

For later testing convenience, a JUnit class library has been customized to guide several important jar packages in a class library,

In this way, future project projects need to write unit tests that directly import the class library without having to re-import the various jar packages.

The Custom class library structure is as follows:

about how to customize the class library, build path--Configure build path ...--...--User Library ...--Next ...

The normal unit test is to create a new source folder and SRC directory under the same package name structure, test Class A, under the corresponding package

Create a test class atest, test the fun method, and create the test method Testfun () accordingly. This article simply learns the JUnit feature, which is not used in this way.

Ok, nonsense, start testing. The article is slightly longer and read as needed.

Assertion-Assertions

In previous versions of JUnit, assertions such as asserttrue,assertequals,assertnull are often used, and it is very easy to know the purpose of a function by its literal meaning.

JUnit 4 combined with hamcrest to exit the more powerful assertion assertthat (), compared to the previous Assertxxx,assertthat code style will become unified, easier to maintain;

with Hamcrest's matchers, can write a lot of flexible tests, the following will be mentioned, another advantage is more inclined to English grammar, not like " the two sides"

(e.g.: assertequals (9, x)) grammatical patterns are clumsy, assertthat use the syntax pattern of the type "principal predicate" (e.g. Assertthat (x, is (9)), which may be influenced by the mother tongue,

the feeling of this merit is not very profound; The following is a practical advantage, Assertthat test failure will provide some readable descriptive error messages,

and Assertxxx will not (of course, can manually write), Assertthat will illustrate; Last but not the least (V~v the English memory of the college Entrance examination),

The sender can implement Matcher interface, custom match, this function is very powerful.

Note: Some classes need to be introduced when testing, some classes (Assert, matchers) are more special, in the way of static introduction,

The advantage is that you can directly use the static methods of these classes (Assertture, assertthat) without using the class name. Method Name.

assertxxx
import static org.junit.assert.*;import org.junit.test;/** * ASSERTXXX Test * @ Author Michael */public class Asserttests {@Testpublic void Testassertarrayequals () {byte[] expected = "trial". GetBytes () ; byte[] actual = "Trial". GetBytes (); Assertarrayequals ("Failure-byte Arrays not Same", expected, actual);} @Testpublic void Testequals () {assertequals ("failure-strings is not Equal", "text", "text");} @Testpublic void Testasserttrue () {asserttrue ("Failure-should be True", true); @Testpublic void Testfalse () {assertfalse ("Failure-should be false", false);} @Testpublic void Testassertnotnull () {assertnotnull ("should not is null", New Object ());} @Testpublic void Testassetnull () {assertnull ("should be NULL", NULL);} @Testpublic void Testassertnotsame () {assertnotsame ("should not is be same object", new Object (), new Object ());} @Testpublic void Testassertsame () {Integer anumber = integer.valueof (985); Assertsame ("should be Same", Anumber, Anumber) ;}}
assertthat
Import static Org.junit.assert.*;import static Org.hamcrest.matchers.*;import Java.util.arrays;import org.junit.Test ;p Ublic class Assertthattests {//junit matchers assertthat@testpublic void testassertthatbothcontainsstring () { Assertthat ("Albumen", Both (containsstring ("a")). and (Containsstring ("B"))); @Testpublic void Testassertthathasitemscontainsstring () {Assertthat (Arrays.aslist ("One", "one", "" "" "", "three"), Hasitems (" One "," three "));} @Testpublic void Testassertthateveryitemcontainsstring () {Assertthat (Arrays.aslist (new string[] {"Fun", "ban", "net"} ), Everyitem (Containsstring ("n")));} /** * Core hamcrest matchers with assertthat * combination of multiple matches */@Testpublic void Testassertthathamcrestcorematchers () {ASSERTTH at ("Good", AllOf (Equalto ("good"), StartsWith ("good")), Assertthat ("Good", Not (AllOf (Equalto ("good"), Equalto ("bad") ))); Assertthat ("Good", AnyOf (Equalto ("good"), Equalto ("bad")), Assertthat (3, not (either (Equalto (6)). or (Equalto (9 ))); Assertthat (New Object (), not (Sameinstance (new Object ())));} /** * Readable Failure message * Assertthat will provide readability error message, Asserttrue will not */@Testpublic void Testfailuremessage () {String s = "C Oour ";//asserttrue (S.contains (" Color ") | | s.contains (" colour ")); Assertthat (S, anyOf (containsstring (" Color "),  Containsstring ("colour")));}}
Kit test-aggregating tests in Suites

If you write a series of test classes (more than 10 or even dozens of), you can't test them one at a time, the suite test will come in handy.

Create an empty class, no need to define anything for this class, just add annotation @runwith (Suite.class) to the head of the class.

@Suite. suiteclasses. Add the classes you want to test in the suiteclasses. This class is created just as a carrier, carrying the above annotations.

Import Org.junit.runner.runwith;import org.junit.runners.suite;import assertions. Asserttests;import assertions. assertthattests; @RunWith (Suite.class) @Suite. suiteclasses ({//Add classes that need to be tested asserttests.class,assertthattests.class// More Test classes}) public class Futuretestsuite {/** * The class remains empty, * used only a holder for the above Annotat Ions. */}

What's the difference between failure and error in JUnit

Sequential testing-Test execution order

There are not many scenarios for sequential testing, and it is only used when you want to write a series of test methods that are executed in a certain order.

Adding @fixmethodorder annotations, there are three common run order definitions within the enumeration class Methodsorters.

DEFAULT, JVM, name_ascending.

Default: Defaults to compare the hashcode value of the method name.

JVM: Depending on the implementation of the JVM, different machines may vary.

name_ascending: Follow the test function method name Ascending.

Import Org.junit.fixmethodorder;import org.junit.test;import org.junit.runners.MethodSorters; @FixMethodOrder ( methodsorters.name_ascending)//@FixMethodOrder (Methodsorters.default)//@FixMethodOrder (METHODSORTERS.JVM) public class Testmethodorder {@Testpublic void TestA () {System.out.println ("First");} @Testpublic void Testb () {System.out.println ("Second");} @Testpublic void Testc () {System.out.println ("Third");}}
Anomaly Testing-Exception testing

when developers write programs, some code may throw exceptions.

How to test if the code throws an exception as we expect, the exception test needs to be used at this point.

@Test annotations have an optional parameter, expected, that specifies the exceptions that might be thrown. For example:

expected Exceptions
Import Java.util.arraylist;import Org.junit.test;public class TestException {@SuppressWarnings ("unused") private double result; @Test (expected = arithmeticexception.class) public void divide () {result = 1/0;} /** * The expected parameter should is used with care.  * The test would pass if any code in the method throws Indexoutofboundsexception */@Test (expected = Indexoutofboundsexcepti on.class) public void Empty () {new arraylist<object> (). get (0);}}

However, the expected parameter should be used with caution, because if any code in the test method throws expected the specified exception,

The test passes, and the exception that the code throws is not exactly located. For long-term consideration, ExpectedException rule is recommended.

About rule is described in another article.

exceptedexception Rule

The above test method is suitable for simple test examples, but it has some limitations, such as the inability of developers to test exception information.

Of course junit3.x provides Try/catch idiom can predict anomalies and exception information. The JUNIT4 provides the expectedexception rule.

the difference is that JUNIT4 expectedmessage can predict the exception information that may be thrown, and can also cooperate with Hamcrest Matchars. Use,

write more flexible tests. For example:

Import static Org.hamcrest.matchers.containsstring;import Java.util.arraylist;import Java.util.list;import Org.junit.rule;import Org.junit.test;import Org.junit.rules.expectedexception;public class TestExceptionRule {// Expected Exception rule@rulepublic ExpectedException thrown =expectedexception.none ();/** * This Rule lets you indicate no T exception you is expecting, * but  also the exception message is expecting: */@Testpublic void should Testexceptionmessage () {list<object> List = new arraylist<object> (); Thrown.expect ( Indexoutofboundsexception.class), Thrown.expectmessage ("index:0, size:0"); Thrown.expectmessage (ContainsString (" Size:0 ")); List.get (0);}}

Test Ignore-Ignore tests

If you want to skip a test method in a test, use the @ignore annotation.

Of course directly comment out @test annotations can also skip the test method, the difference is that

Comments are not displayed in the test results, and using @ignore will show that the method is ignored.

Import Org.junit.ignore;import Org.junit.test;public class Testignore {@Testpublic void TestA () {System.out.println (" Executed ");} @Ignore @testpublic void Testb () {System.out.println ("ignored");}}
Timeout test-timeout for tests

Time- out test, as the name implies, the test method exceeds the specified time will be reported errors, attention is not failures.

Why is JUnit timeout a Error not Failure

developers can set a time-out for a single method, or they can set a uniform time-out for the entire test class.

Set the time-out for a single method, in milliseconds per unit
Import Org.junit.test;public class Testtimeout {@Test (timeout=100) public void Testwithtimeout () {for (;;) {}}}
set the time-out for the entire class, in milliseconds
Import Org.junit.rule;import Org.junit.test;import Org.junit.rules.timeout;public class Testtimeoutrule {public static int n; @Rulepublic timeout globaltimeout = new timeout, @Testpublic void TestInfiniteLoop1 () {n++;for (;;) {}} @Testpublic void TestInfiniteLoop2 () {n++;for (;;) {}}}
Concluding remarks

About parameterized tests, Rules, theories and other features will be introduced in another article.

This article is for the author to learn JUnit's learning notes, there is no misunderstanding deviation, but also hope that the reader pointing to correction.

keeps the bar green to keep the code clean.

JUNIT4 Unit Test Basics

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.