JUnit Unit Test

Source: Internet
Author: User
Tags getzip

OverviewJUnit is a unit test framework for the Java language. It was established by Kent Beck and Erich Gamma

GitHub Address

Https://github.com/junit-team/junit4

JUnit official website

Http://junit.org/junit4

Note: Mainly translation, but there is no translation of the full text.

Getting StartedThis small example shows how to write a unit test. You need to install the JDK with a text editor.
Get readyCreate a Jnnit-example folder, download and introduce JUnit's jar package, all the files are created under that folder, and the commands are executed there.
Create a Caculator.java file
public class Calculator {public  int evaluate (String expression) {    int sum = 0;    For (String summand:expression.split ("\\+"))      sum + = integer.valueof (summand);    return sum;  }}
Compiling files
Javac Calculator.java
The Calculator.class file is generated after compilation
Creating unit Tests
Import static Org.junit.assert.assertequals;import Org.junit.test;public class Calculatortest {  @Test  public void Evaluatesexpression () {    Calculator Calculator = new Calculator ();    int sum = calculator.evaluate ("1+2+3");    Assertequals (6, sum);}  }
compiling on Linux or Mac
JAVAC-CP.: junit-4. Xx.jar Calculatortest.java
Compiling on Windows
JAVAC-CP.; Junit-4. Xx.jar Calculatortest.java
Performing unit testson a Linux or Mac platform
JAVA-CP.: junit-4. Xx.jar:hamcrest-core-1.3.jar Org.junit.runner.JUnitCore Calculatortest
on the Winddows platform
JAVA-CP.; Junit-4. Xx.jar;hamcrest-core-1.3.jar Org.junit.runner.JUnitCore Calculatortest
Output
JUnit version 4.12.time:0,006ok (1 test)
This is the result of the successful execution of the output. If an error is performed, the output sample of the error
JUnit version 4.12.etime:0,007there was 1 failure:1) evaluatesexpression (calculatortest) Java.lang.AssertionError: Expected:<6> but was:<-6> at  org.junit.Assert.fail (assert.java:88)  ... Failures!!! Tests Run:1,  failures:1
the error message prompts us that the expected result is 6, but the actual output is-6, code 88 lines. Enclosed use example of a closed Testtunner
usually we need subclasses of each abstract class, using enclosed Runer, you can use the static inner class of the same test case class.
public class Address implements Serializable, comparable<address> {private static final long Serialversionuid =    1L;    Private final String Address1;    Private final String city;    Private final String state;    Private final String zip;        Private Address (builder builder) {this.address1 = Builder.address1;        this.city = builder.city;        This.state = builder.state;    This.zip = Builder.zip;    } public String GetAddress1 () {return address1;    } public String getcity () {return city;    } public String GetState () {return state;    } public String Getzip () {return zip; } @Override public int compareTo (Address) {return Comparisonchain.start (). Compare (This.zip, that.zip). C Ompare (This.state, that.state). Compare (This.city, that.city). Compare (This.address1, that.address1). Result (    ); @Override public boolean equals (Object obj) {if (obj = = null) {return false;}        if (getclass () = Obj.getclass ()) {return false;}        Final Address that = (Address) obj; Return com.google.common.base.Objects.equal (This.address1, that.address1) && com.google.common.base .                 Objects.equal (this.city, that.city) && com.google.common.base.Objects.equal (this.state, That.state)    && com.google.common.base.Objects.equal (This.zip, that.zip); } @Override public int hashcode () {return Com.google.common.base.Objects.hashCode (GetAddress1 (), getcity (),    Getcity (), GetState (), Getzip ()); } @Override Public String toString () {return com.google.common.base.Objects.toStringHelper (this). AddValue (GE    TAddress1 ()). AddValue (Getcity ()). AddValue (GetState ()). AddValue (Getzip ()). ToString ();        } public static class Builder {private String address1;        Private String City;        Private String State;        Private String zip; Public Builder Address1 (String Address1) {this.address1 = Address1;        return this;        Public address build () {Return to new address (this);            } public Builder City (String city) {this.city = city;        return this;            Public Builder State (String state) {this.state = state;        return this;            Public Builder Zip (String zip) {this.zip = zip;        return this; }    }}

/** * the Class addresstest.     */@RunWith (Enclosed.class) public class Addresstest {/** * the class addresscomparabilitytest.        */public static class Addresscomparabilitytest extends Comparabilitytestcase<address> {@Override Protected Address createequalinstance () throws Exception {return new Address.builder (). Address1 ("2802 South Ha        Vana Street "). (" Aurora "). State (" CO "). Zip (" 80014 "). Build (); } @Override protected Address creategreaterinstance () throws Exception {return new Address.build        ER (). Address1 ("9839 Carlisle Boulevard NE"). ("Albuquerque"). State ("NM"). Zip ("87110"). Build (); } @Override protected Address createlessinstance () throws Exception {return new Address.builder (        ). Address1 ("Broad St"). ("Nashua"). State ("NH"). Zip ("03064"). Build ();     }}/** * the Class addressequalshashcodetest. */public static class Addressequalshashcodetest extends equalshashcodetestcase {@Override protected Address CreateInstance () throws Exception {return        New Address.builder (). Address1 ("2802 South Havana Street"). ("Aurora"). The state ("CO"). Zip ("80014"). Build (); } @Override protected Address createnotequalinstance () throws Exception {return new Address.buil        Der (). Address1 ("9839 Carlisle Boulevard NE"). ("Albuquerque"). State ("NM"). Zip ("87110"). Build ();     }}/** * the Class addressserializabilitytest. */public static class Addressserializabilitytest extends Serializabilitytestcase {@Override protected S Erializable CreateInstance () throws Exception {return new Address.builder (). Address1 ("9839 Carlisle Boulevard        NE "). (" Albuquerque "). State (" NM "). Zip (" 87110 "). Build ();        }} public static class Addressmisctest {private address address;         /** * Setup.    * * @throws Exception the Exception     */@Before public void SetUp () throws Exception {address = new Address.builder (). Address1 ("        9839 Carlisle Boulevard NE "). City (" Albuquerque "). The state (" NM "). Zip (" 87110 "). Build ();         }/** * Test Builder. */@Test public void Testbuilder () {Assertthat (Address.getaddress1 (), is ("9839 Carlisle Boulevar            D NE "));            Assertthat (Address.getcity (), is ("Albuquerque"));            Assertthat (Address.getstate (), is ("NM"));        Assertthat (Address.getzip (), is ("87110")); } @Test public void testtostring () {Assertthat (address.tostring (), is ("address{9839 Carlisle Bou        Levard NE, Albuquerque, NM, 87110} ")); }    }}
Test Suite Suitewith suite, you can build a suite with multiple unit tests, using annotations in JUNIT4, related to the Test.suite () method in JUnit3.8,using the example
Import Org.junit.runner.runwith;import org.junit.runners.Suite; @RunWith (Suite.class) @Suite. suiteclasses ({  Testfeaturelogin.class,  Testfeaturelogout.class,  Testfeaturenavigate.class,  Testfeatureupdate.class}) public class Featuretestsuite {  //The class remains empty,  //used only as a holder for The above annotations}
Assert method AssertJUnit provides overloaded assertion methods for basic types and objects, as well as arrays (primitive types or objects). The order of the parameters is the expected and actual values. The first value that is optional is the message of the error condition. There is a slightly different assertion that assertthat it requires is an optional failure message, the actual return value, and a Matcher object. It is worth noting that the expected and actual is contrary to other assertion methods. example of a representative assertion method
public class Asserttests {@Test public void testassertarrayequals () {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 is not Equal", "text", "Te  XT ");  } @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 ("albumen", b  Oth (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 ()))); } @Test public void TestAsserttrue () {org.junit.Assert.assertTrue ("Failure-should be True", true); }}
use of Assumeassume is the assumption that JUnit provides a set of tools for judging whether the entry of a test case has a business meaning, and if the entry does not meet expectations, it throws Assumptionviolatedexception, The default Blockjunit4classrunner and its subclasses catch the exception and skip the current test, and if you use a custom runner you cannot guarantee the behavior, depending on the implementation of runner.
The validation methods provided by assume include: Assumetrue/assumefalse, Assumenotnull, Assumethat, Assumenoexception. The specific meaning is relatively simple. use of RuleA rule that defines the behavior of a test method, JUNIT4 contains two annotations @rule and @classrule are used to decorate field or return rule method,rule is a set of shared classes that implement Testrule interfaces, providing validation, Monitor TestCase and external resource management capabilities. JUnit provides the following rule implementations, which you can implement yourself if necessary.
Verifier: Verifies the correctness of test execution results.
Errorcollector: Collects error messages that occur in test methods, tests are not interrupted, and marks fail if errors occur.
ExpectedException: Provides flexible exception verification capabilities.
Timeout: The rule used to test timeouts.
Externalresource: External resource management.
Temporaryfolder: Create and delete new temporary directories before and after JUnit tests are executed.
Testwatcher: Monitor the various stages of the test method life cycle.
TestName: Provides the ability to obtain a test name during the execution of a test method.
There are too many sample code to paste the code.Details:Https://github.com/junit-team/junit4/wiki/Rulestest that throws an exception
@Test (expected = indexoutofboundsexception.class) public void Empty () {      new arraylist<object> (). get (0);}
expected parameters should be used with caution, the above code when the indexoutofboundsexception exception thrown when the test passed. It is more recommended to use ExpectedException rule
@Rulepublic expectedexception thrown = Expectedexception.none (), @Testpublic void Shouldtestexceptionmessage () throws indexoutofboundsexception {    list<object> List = new arraylist<object> ();    Thrown.expect (indexoutofboundsexception.class);    Thrown.expectmessage ("index:0, size:0");    List.get (0); Execution'll never get past this line}
This blog has a detailed description of the original blog
Timeout Processing
@Test (timeout=1000) public void Testwithtimeout () {  ...}
You can also specify that the timeout is set in milliseconds, and a timeout exception is thrown if the time limit is exceeded. if the test run exceeds the specified time, it will cause the test to fail and JUnit will break the test thread.
Timeout RuleTime-out rules apply to all test methods in a class
Import Org.junit.rule;import Org.junit.test;import Org.junit.rules.timeout;public class Hasglobaltimeout {    public static String log;    Private final Countdownlatch latch = new Countdownlatch (1);    @Rule public    Timeout globaltimeout = Timeout.seconds (ten);//Seconds Max per method tested    @Test public    Voi D Testsleepfortoolong () throws Exception {        log + = "Ran1";        TimeUnit.SECONDS.sleep (100); Sleep for the Seconds    }    @Test public    void Testblockforever () throws Exception {        log + = "ran2"; 
   
    latch.await (); would block     }}
   


Welcome to scan QR Code, follow public account

JUnit Unit Test

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.