JUnit Test Highlights

Source: Internet
Author: User

junit Test Highlights


Preface:

A program from a well-designed state to start, with the new features continue to join, the program gradually lost its original structure, and eventually become mess. So in the development process, for programmers, testing is very important. Anyway, start JUnit's test.

It is convenient to use JUnit for unit testing in Eclipse/myeclipse, especially after JUNIT4 has introduced many annotation annotations.

One, the core-assertion

Assertions are the core implementation of writing test cases, that is, what the expected value is, and how much is the result of the test to determine whether the test passed.

1. Assertion Core Method

assertarrayequals (expecteds, actuals) to see if two arrays are equal.
assertequals (expected, actual) to see if two objects are equal. The Equals () method, similar to string comparisons,
assertnotequals (first, second) to see whether two objects are not equal.
assertnull (object) to see if the object is empty.
assertnotnull (object) to see if the object is not empty.
assertsame (expected, actual) to see whether references to two objects are equal. Similar to using "= =" to compare two objects
assertnotsame (Unexpected, actual) to see whether references to two objects are not equal. Similar to using "! =" to compare two objects
asserttrue (condition) to see if the run result is true.
assertfalse (condition) to see if the run result is false.
assertthat (Actual, matcher) See if the actual value meets the specified condition
fail () Let Test Failed

2. Example


Package Test;import static org.hamcrest.corematchers.*;import static Org.junit.assert.*;import java.util.Arrays; Import Org.hamcrest.core.combinablematcher;import Org.junit.test;public class Asserttests {@Test public void Testasser    Tarrayequals () {byte[] expected = "trial". GetBytes ();    Byte[] actual = "Trial". GetBytes ();  Org.junit.Assert.assertArrayEquals ("Failure-byte Arrays not Same", expected, actual);  } @Test public void Testassertequals () {org.junit.Assert.assertEquals ("failure-strings not Same", 5l, 5l);  } @Test public void Testassertfalse () {Org.junit.Assert.assertFalse ("Failure-should is false", false);  } @Test public void Testassertnotnull () {Org.junit.Assert.assertNotNull ("should is not NULL", New Object ()); } @Test public void Testassertnotsame () {Org.junit.Assert.assertNotSame ("should is not being same object", new object (), n  EW Object ()); } @Test public void Testassertnull () {Org.junit.Assert.assertNull ("Should is null", NULL); } @Test public void Testassertsame () {Integer anumber = integer.valueof (768);  Org.junit.Assert.assertSame ("Should be Same", anumber, Anumber); }//JUnit matchers assertthat @Test public void testassertthatbothcontainsstring () {Org.junit.Assert.assertThat ("a  Lbumen ", Both (containsstring (" a ")). and (Containsstring (" B ")); } @Test public void testassertthathasitemscontainsstring () {Org.junit.Assert.assertThat (Arrays.aslist ("One", "one", "  "Three"), Hasitems ("One", "three")); } @Test public void testassertthateveryitemcontainsstring () {Org.junit.Assert.assertThat (Arrays.aslist (new string[]  {"Fun", "ban", "net"}), Everyitem (Containsstring ("n")); }//Core hamcrest matchers with assertthat @Test public void Testassertthathamcrestcorematchers () {Assertthat ("goo    D ", AllOf (Equalto (" good "), StartsWith (" good "));    Assertthat ("Good", Not (AllOf (Equalto ("bad"), Equalto ("good")));    Assertthat ("Good", AnyOf (Equalto ("bad"), Equalto ("good")); Assertthat (7,Not (combinablematcher.<integer> either (Equalto (3)). or (Equalto (4)));  Assertthat (New Object (), not (Sameinstance (new Object ()))); }}

Second, the core--annotations

1. Description

@Before Initialize method
@After Freeing resources
@Test Test method, where you can test for expected exceptions and time-outs
@Ignore Ignored test methods
@BeforeClass For all tests, execute only once and must be static void
@AfterClass For all tests, execute only once and must be static void
@RunWith Specifies that a test class uses a runner
@Parameters To specify a test data collection for a test class
@Rule Allows flexibility to add or redefine the behavior of each test method in a test class
@FixMethodOrder Specify the order in which test methods are executed

2. Execution order

A Test class unit test is executed in the following order:

@BeforeClass –> @Before –> @Test –> @After –> @AfterClass

The order in which each test method is called is:

@Before –> @Test –> @After

3. Example


Package Test;import static Org.junit.assert.*;import org.junit.*;p Ublic class Jdemotest {@BeforeClasspublic static void Setupbeforeclass () throws Exception {System.out.println ("================in beforeclass================");} @AfterClasspublic static void Teardownafterclass () throws Exception {System.out.println ("================in afterclass================= ");} @Beforepublic void before () {System.out.println ("in Before");} @Afterpublic void After () {System.out.println (' in After ');} @Test (timeout = 10000) public void Testadd () {Jdemo a = new Jdemo (); Assertequals (6, A.add (3, 3)); System.out.println ("in Test----Add");} @Testpublic void Testdivision () {Jdemo a = new Jdemo (); Assertequals (3, A.division (6, 2)); System.out.println ("in Test----Division");} @Ignore @testpublic void Test_ignore () {Jdemo a = new Jdemo (); Assertequals (6, A.add (1, 5)); System.out.println ("in Test_ignore");} @Testpublic void Teest_fail () {fail ();}} Class Jdemo extends Thread {int result;public int add (int a, int b) {try {SLEEP (+); result = a + b;} catch (Interruptedexception e) {}return result;} public int Division (int a, int b) {return result = A/b;}}

Execution Result:

=================in beforeclass================in beforein Test----Addin afterin beforein test----divisionin After=== ================in afterclass=================



The upper left red box in the figure represents the JUnit run result, 5 successes (one ignore), 1 errors, and 1 failures. (Note that errors and failures are not the same, the error indicates that the code has an error, and failure indicates that the test method test failed)

The lower left red box indicates the running state of each test method, and you can see that the respective icons for success, error, failure, and failure are different, and you can see the run time.

The right part is the exception stack, which allows you to view exception information.

Iii. Summary of examples

1. Parametric testing

Sometimes a test method, different parameter values will produce different results, then we have to test the full, will be a number of parameter values are written out and assert the test, which sometimes inevitably time-consuming laborious, this is we can use parametric testing to solve the problem. Parametric testing is like passing a set of "input values, expectations" to a test method to achieve a one-time test.

Package Test;import static Org.junit.assert.*;import Java.util.arrays;import Org.junit.test;import Org.junit.runner.runwith;import Org.junit.runners.parameterized;import org.junit.runners.Parameterized.Parameters; @RunWith (parameterized.class) public class Fibonaccitest {@Parameters ( Name = "{Index}: fib ({0}) ={1}") public static iterable<object[]> data () {return arrays.aslist (new object[    [] {{0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}});    } private int input;    private int expected;        public fibonaccitest (int input, int expected) {this.input = input;    this.expected = expected;    } @Test public void Test () {assertequals (expected, Fibonacci.compute (input)); }}class Fibonacci {public static int compute (INT. input) {int Result;switch (input) {case 0:result = 0;break;case 1:case 2: result = 1;break;case 3:result = 2;break;case 4:result = 3;break;case 5:result = 5;break;case 6:result = 8;break;deFault:result = 0;} return result;}}
@Parameters annotation parameter name, which is actually the test method names. Because a test () method completes all the tests, what if there is a problem with a set of test data, what should be presented in the JUnit results page? So using name is actually the name of the test method that distinguishes each test data.

2. Packaging test

Similarly, if a project has many test cases, it can be cumbersome to test, so a packaged test is a one-time test to complete all the test cases contained in the package.

Package Test;import Org.junit.runner.runwith;import org.junit.runners.Suite; @RunWith (Suite.class) @ Suite.suiteclasses ({asserttests.class, Fibonaccitest.class, jdemotest.class}) public class Allcasetest {}

This feature also requires the use of a special runner, which requires a parameter suite.class to be passed to the @runwith annotation. At the same time, we need another annotated @suite.suiteclasses to show that this class is a packaged test class. and pass the class that needs to be packaged as a parameter to the annotation. As for allcasetest a class name casually, the content is empty. Run the Allcasetest class to complete the packaging test

3. Anomaly Testing

Anomaly testing differs from normal assertion testing in a total of three methods, the most flexible of which is the third, which can be used in conjunction with assertions

The first type:

  @Test (expected= indexoutofboundsexception.class) public   Void Empty () {        new arraylist<object> (). Get (0) ;   }

The second type:

  @Test public  void Testexceptionmessage () {      try {          new arraylist<object> (). get (0);          Fail ("expected an indexoutofboundsexception to be thrown");      } catch (Indexoutofboundsexception anindexoutofboundsexception) {          assertthat ( Anindexoutofboundsexception.getmessage (), is ("index:0, size:0"));      }  }

The third type:

    @Rule public    ExpectedException thrown = Expectedexception.none ();    @Test public    void Shouldtestexceptionmessage () throws indexoutofboundsexception {        list<object> List = New Arraylist<object> ();        Thrown.expect (indexoutofboundsexception.class);        Thrown.expectmessage ("index:0, size:0");        List.get (0);        Assert.assertequals (1, list.get (0));    }

In each of these methods, both expected and expect indicate the expected exception, and if a method throws an exception when the argument is a value, then the first method must be used to write a test method for the parameter to test the exception. and cannot be written together with other parameter values in a test method, so it seems cumbersome. The second approach solves this problem, but the wording is not only cumbersome but also not conducive to understanding. The third type of crime, not only can dynamically change the expected thrown exception, and the assertion statement is also very good, so it is recommended to use this method to test the exception.

4. Time-Limited testing

Sometimes you need to use a time-limited test to prevent a dead loop or a method from executing too long (or checking the efficiency of the method). As the name implies, the test fails when the set time is exceeded. There are two ways to do it.

The first type:

@Test (timeout=1000) public void Testwithtimeout () {  ...}

The second type:
public class Hasglobaltimeout {public    static String log;    @Rule public    Timeout globaltimeout = new timeout (10000),//Seconds Max per method tested    @Test public    Void TestInfiniteLoop1 () {        log + = "Ran1";        for (;;) {        }    }    @Test public    void TestInfiniteLoop2 () {        log + = "ran2";        for (;;) {        }    }}

PostScript:

It is because of the openness and simplicity of junit that this introductory article is introduced. But the technology is constantly being updated, and we don't have a very deep understanding of the test; we can simplify a complex concept into a very easy to understand word.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JUnit Test Highlights

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.