Java Junit Basic Notes

Source: Internet
Author: User
Tags assert object object

Junit1. Concept

JUnit is a unit test framework for the Java language.
Unit Tests: Unit Tests (English: units testing), also known as module tests, are testing for correctness checks of program modules (the smallest unit of software design). The program unit is the smallest testable part to be applied. In procedural programming, a unit is a single program, function, process, etc. for object-oriented programming, the smallest element is a method, including a base class (superclass), an abstract class, or a method in a derived class (subclass).

2. JUnit Features
    • Test tools
    • Test suite
    • Test Runner
    • Test classification
3. API annotations
Serial Number Notes Description
1 * * @Test * * Attached to the public void method of JUnit as a test case.
2 * * @Before * * Indicates that it must be performed before each test in order to perform some necessary prerequisites for testing.
3 * * @BeforeClass * * dependent on a static method, it must be performed before all the classes are measured. Typically, test the compute shared configuration method (connect to a database).
4 * * @After * * Represents the execution after each test, such as resetting or deleting certain variables after each test.
5 * * @AfterClass * * Executes after all test cases and can be used to clean up the build method, such as disconnecting a database. Methods that are attached as @beforeclass must be static.
6 * * @Ignore * * When you want to temporarily disable a particular test execution, the method that is annotated as @ignore will not be executed.
  • code example:

    Import org.junit.*;/*** Created by Administrator on 2017/11/1 0001.*/public class Testannotation {//indicates that this is attached to a static method that must be executed once and    Before all tests of the class. When this happens, it is common to test the compute shared configuration method (such as connecting to a database) @BeforeClass public static void Beforeclass () {System.out.println ("Execute B    Eforeclass "); }//When all tests need to be performed after the JUnit test case class, Afterclass annotations can be used to clean up the build method,//(from the database such as disconnecting).    Note: Methods that are attached to this annotation (similar to beforeclass) must be defined as static.    @AfterClass public static void Afterclass () {System.out.println ("execute Afterclass");    The//before comment indicates that the method must be executed before each test in the class in order to perform some of the necessary prerequisites for testing.    @Before public void before () {System.out.println ("execute before"); The//after comment indicates that the method executes after each test (such as resetting certain variables after performing each test, deleting temporary variables, and so on) @After public void after () {System.out.println ("exec    Ute after ");    }//The test note indicates that the public invalid method it is attached to can act as a test case.    @Test public void Test () {System.out.println ("execute Test");    } @Test public void Test1 () {System.out.println ("execute test1"); You can use ignore annotations when you want to temporarily disable a specific test execution. Each is annotated as @ignoThe re method will not be executed.    @Ignore public void Ignoretest () {System.out.println (); }}
    import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;/*** Created by Administrator on 2017/11/1 0001.*/public class TestRunner2 {    public static void main(String[] args) {        Result result= JUnitCore.runClasses(TestAnnotation.class);        for (Failure failure:result.getFailures()){            System.out.println(failure.toString());        }        System.out.println(result.wasSuccessful());    }}
  • Operation Result:

    execute beforeClassexecute beforeexecute testexecute afterexecute beforeexecute test1execute afterexecute afterClasstrue
  • JUnit's execution process
    • Beforeclass first execution, only once
    • Afterclass last execution, only once
    • Before is executed before each test
    • After each test is executed
    • Each test executes between after and before
Assertion
Serial Number Method Description
1 Assertequals (Boolean expected, Boolean actual) Check whether two variables or equations are balanced
2 Asserttrue (Boolean expected, Boolean actual) Check if the condition is true
3 Assertfalse (Boolean condition) Check whether the condition is false
4 Assertnotnull (Object object) Checks if the variable is not empty
5 Assertnull (Object object) Check if the variable is empty
6 Assertsame (object expected, object actual) Checks whether two references point to the same object
7 Assertnotsame (object expected, object actual) Checks if two references do not point to the same object
8 Assertarrayequals (Expectedarray, Resultarray) Check if two arrays are equal
    • code example

      import org.junit.Test;import static org.junit.Assert.*;public class TestAssertions {    @Test    public void testAssertions(){        String str1=new String("abc");        String str2=new String("abc");        String str3=null;        String str4="abc";        String str5="abc";        int val1=5;        int val2=6;        String[] expectedArray={"one","two","three"};        String[] resultArray={"one","two","three"};        assertEquals(str1,str2);        assertTrue(val1<val2);        assertFalse(val1>val2);        assertNotNull(str1);        assertNull(str3);        assertSame(str4,str5);        assertNotSame(str1,str3);        assertArrayEquals(expectedArray,resultArray);    }}
4. Perform the test

The test case is executed through the Junitcore class, which is the appearance class for JUnit to run the test. For a one-time test run, you can use the static method: Runclasses (class[])

5. Kit Testing

It means bundling several unit test cases and executing them together. * * @RunWith * * and * * @Suite * * can be used to run suite tests together

  • code example

    /*** Created by Administrator on 2017/11/1 0001.* 被测试类*/public class MessageUtil {    private String message;    public MessageUtil(String message){        this.message=message;    }    public String printMessage(){        System.out.println(message);        return message;    }    public String salutationMessage(){        message="Hi!"+message;        System.out.println(message);        return message;    }}
    import org.junit.Assert;import org.junit.Test;/*** Created by Administrator on 2017/11/1 0001.*/public class TestJunit {    String message="Robert";    MessageUtil messageUtil=new MessageUtil(message);    @Test    public void testPrintMessage(){//        message="New Word";        System.out.println("Inside testPrintMessage()");        Assert.assertEquals(message,messageUtil.printMessage());    }}
    import org.junit.Assert;import org.junit.Test;/*** Created by Administrator on 2017/11/1 0001.*/public class TestJunit1 {    String message = "Robert";    MessageUtil messageUtil=new MessageUtil(message);    @Test    public void testSalutationMessage(){        System.out.println("Inside testSalutationMessage()");        message="Hi!"+"Robert";        Assert.assertEquals(message,messageUtil.salutationMessage());    }}

Test Execution class:
```
Import Org.junit.runner.JUnitCore;
Import Org.junit.runner.Result;
Import Org.junit.runner.notification.Failure;

    /**    * Created by Administrator on 2017/11/1 0001.    */    public class TestRunner2 {        public static void main(String[] args) {            Result result= JUnitCore.runClasses(JunitTestSuite.class);            for (Failure failure:result.getFailures()){                System.out.println(failure.toString());            }            System.out.println(result.wasSuccessful());        }    }```
    • Run results

      Inside testPrintMessage()RobertInside testSalutationMessage()Hi!Roberttrue
6. Ignore the test
    • A test method that contains * * @Ignore * * Comments will not be executed
    • If a test class has a * * @Ignore * * Comment, its test method will not be executed
7. Time Test
  • The **timeout** parameter is used with the @test annotation, and when a test case takes more time than the specified number of milliseconds, JUnit will automatically mark it as failed.
  • code example:

     /*** Created by Administrator on 2017/11/1 0001.*/public class Messageutil {private String message;    Public Messageutil (String message) {this.message=message;        } public void Printmessage () {System.out.println (message);    while (true); } public String Salutationmessage () {message= "hi!"        +message;        SYSTEM.OUT.PRINTLN (message);    return message; }}
      Import Org.junit.assert;import org.junit.test;/*** Created by Administrator on 2017/11/1 0001.*/public class    TESTJUNIT4 {String message = "Robert";    Messageutil messageutil=new messageutil (message);        @Test (timeout = +) public void Testprintmessage () {System.out.println ("Inside testprintmessage");    Messageutil.printmessage ();        } @Test public void Testsalutationmessage () {System.out.println ("Inside testsalutationmessage"); Message= "hi!"        + "Robert";    Assert.assertequals (Message,messageutil.salutationmessage ()); }}
    import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;/*** Created by Administrator on 2017/11/1 0001.*/public class TestRunner2 {    public static void main(String[] args) {        Result result= JUnitCore.runClasses(TestJunit4.class);        for (Failure failure:result.getFailures()){            System.out.println(failure.toString());        }        System.out.println(result.wasSuccessful());    }}
  • Run results

    Inside testSalutationMessageHi!RobertInside testPrintMessageRoberttestPrintMessage(TestJunit4): test timed out after 1000 millisecondsfalse
8. Anomaly Testing
  • The expected parameter is used in conjunction with the @test annotation to test whether the code throws the exception you want to get.

  • code example

     /*** Created by Administrator on 2017/11/1 0001.*/public class Messageutil {private String message;    Public Messageutil (String message) {this.message=message;        public void Printmessage () {System.out.println (message);//Return message;//while (true);        int a=0;    int b=1/a; } public String Salutationmessage () {message= "hi!"        +message;        SYSTEM.OUT.PRINTLN (message);    return message; }}
    import org.junit.Assert;import org.junit.Test;/*** Created by Administrator on 2017/11/1 0001.*/public class TestJunit5 {    String message = "Robert";    MessageUtil messageUtil=new MessageUtil(message);    @Test(expected = ArithmeticException.class)    public void testPrintMessage(){        System.out.println("Inside testPrintMessage");        messageUtil.printMessage();    }    @Test    public void testSalutationMessage(){        System.out.println("Inside testSalutationMessage");        message="Hi!"+"Robert";        Assert.assertEquals(message,messageUtil.salutationMessage());    }}
  • Run results

    Inside testSalutationMessageHi!RobertInside testPrintMessageRoberttrue
9. Parametric testing
  • Parametric testing allows developers to run the same test case repeatedly using different values.
    • Use * * @RunWith (parameterized.class) * * To annotate the test class
    • Creates a public static method by the * * @Parameterized. parameters** annotation that returns a collection of objects (arrays) to be used as a test data collection.
    • Create a public constructor to receive and store test data.
    • Run repeatedly with regular meetings to create an instance variable for each set of test data
    • Create your test cases using instance variables as sources of test data
  • code example
    Judging is not a prime number:

    public class PrimeNumberChecker {    public Boolean validate(final Integer primeNumber){        for (int i = 2; i < (primeNumber / 2); i++) {            if (primeNumber%i==0){                return false;            }        }        return true;    }}
    Import Org.junit.assert;import org.junit.before;import Org.junit.test;import Org.junit.runner.runwith;import Org.junit.runners.parameterized;import java.util.arrays;import java.util.collection;/*** Created by Administrator on    2017/11/1 0001.*/@RunWith (parameterized.class) public class Primenumbercheckertest {private Integer inputnumber;    Private Boolean Expectedresult;    Private Primenumberchecker Primenumberchecker;        @Before public void Initialize () {System.out.println ("initialize");    Primenumberchecker=new Primenumberchecker ();        } public primenumbercheckertest (Integer Inputnumber,boolean expectedresult) {System.out.println ("construct");        This.inputnumber=inputnumber;    This.expectedresult=expectedresult;                } @Parameterized. Parameters public static Collection Primenumbers () {return arrays.aslist (new object[][]{              {2,true}, {6,true}, {19,true}, {22,true},  {23,true}});        } @Test public void Testprimenumberchecker () {System.out.println ("Test");        SYSTEM.OUT.PRINTLN ("Parameterized number is:" + inputnumber);    Assert.assertequals (Expectedresult, Primenumberchecker.validate (Inputnumber)); }}
    import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;/*** Created by Administrator on 2017/11/1 0001.*/public class TestRunner2 {    public static void main(String[] args) {        Result result= JUnitCore.runClasses(PrimeNumberCheckerTest.class);        for (Failure failure:result.getFailures()){            System.out.println(failure.toString());        }        System.out.println(result.wasSuccessful());    }}
  • Run results

    constructinitializetestParameterized Number is : 2constructinitializetestParameterized Number is : 6constructinitializetestParameterized Number is : 19constructinitializetestParameterized Number is : 22constructinitializetestParameterized Number is : 23testPrimeNumberChecker[1](PrimeNumberCheckerTest): expected:<true> but was:<false>testPrimeNumberChecker[3](PrimeNumberCheckerTest): expected:<true> but was:<false>false

Java Junit Basic notes

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.