JUnit4 note

What is JUnit

JUnit is a Regression Testing Framework used by developers to implement unit testing in Java and accelerate programming speed and increase the quality of codejava

features:

Fixtures:

is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable.函數

Test suites:

Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.工具

Test runners:

Test runner is used for executing the test cases. Here is an example which assumes TestJunit test class already exists測試

JUnit classes:

JUnit classes are important classes which is used in writing and testing JUnits. Some of the important classes are:ui

  • Assert which contain a set of assert methods.this

  • TestCase which contain a test case defines the fixture to run
    multiple tests.code

  • TestResult which contain methods to collect the results of executing
    a test case.orm

示例代碼

最純淨的例子

// 測試case寫法1:
// 繼承TestCase ,測試方法 public void testXXX(){} 形式
import org.junit.Assert;
import junit.framework.TestCase;
public class TestJunit1 extends TestCase{

    public void testAdd(){
        String str = "JUnit is working fine";
        Assert.assertEquals("JUnit is working fine", str);
    }
}

// 測試case寫法2
// 使用@Test 註解
import org.junit.Assert;
import org.junit.Test;
public class TestJunit1{
    @Test
    public void testAdd(){
        String str = "JUnit is working fine";
        Assert.assertEquals("JUnit is working fine", str);
    }
}
// JUnitCore 這裏做爲門面類用來執行測試用例
// JUnitCore is a facade for running tests. It supports running JUnit 4 tests, 
// JUnit 3.8.x tests, and mixtures. To run tests from the command line, run java 
// org.junit.runner.JUnitCore TestClass1 TestClass2 .... For one-shot test runs, use the // static method runClasses(Class []). If you want to add special listeners, create an 
// instance of org.junit.runner.JUnitCore first and use it to run the tests.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

愛上簡單註解

// 測試類
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class JunitAnnotation {
    //Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class.
    @BeforeClass
    public static void beforeClass(){
        System.out.println("in before class");
    }
    //This will perform the method after all tests have finished. This can be used to perform clean-up activities.
    @AfterClass
    public static void afterClass(){
        System.out.println("in after class");
    }
    //Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method.
    @Before
    public void before(){
        System.out.println("in before");
    }
    //If you allocate external resources in a Before method you need to release them after the test runs. 
    //Annotating a public void method with @After causes that method to be run after the Test method.
    @After
    public void after(){
        System.out.println("in after");
    }
    //The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.
    @Test
    public void test(){
        System.out.println("in test");
    }
    //The Ignore annotation is used to ignore the test and that test will not be executed.
    @Ignore
    public void ignoreTest(){
        System.out.println("in ignore test");
    }
}
咱們仍是用JUnitCore來運行這個測試:
控制檯輸出:
in before class
in before
in test
in after
in after class

豪華套裝(TestSuite)

先上來兩個測試用例
測試用例1
import org.junit.Assert;
import junit.framework.TestCase;
public class TestJunit1 extends TestCase{

    public void testAdd(){
        String str = "JUnit is working fine";
        Assert.assertEquals("JUnit is working fine", str);
    }
}
測試用例2
import org.junit.Test;
import static org.junit.Assert.*;
public class TestJunit2 {
   @Test
   public void testAdd() {
      //test data
      int num= 5;
      String temp= null;
      String str= "Junit is working fine";

      //check for equality
      assertEquals("Junit is working fine2", str);
      
      //check for false condition
      assertFalse(num > 6);

      //check for not null value
      assertNotNull(str);
   }
}
關鍵在於TestSuite的寫法

方式一:
import junit.framework.*;

public class JunitTestSuite {
    public static void main(String[] a) {
        // add the test's in the suite
        TestSuite suite = new TestSuite(TestJunit1.class, TestJunit2.class, TestJunit3.class);
        TestResult result = new TestResult();
        suite.run(result);
        System.out.println("Number of test cases = " + result.runCount());
    }
}

直接就能夠跑來了
方式二(註解形式):
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({ TestJunit1.class, TestJunit2.class })

// JUnit suite test
public class JunitTestSuite {

}

而後用JunitCore就能夠跑起來了

參數化測試

Junit 4 has introduced a new feature Parameterized tests.Parameterized
tests allow developer to run the same test over and over again using
different values. There are five steps, that you need to follow to
create Parameterized tests.繼承

示例代碼(校驗是不是質數的參數化測試)

// 工具類
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 static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

//步驟一:爲準備使用參數化測試的測試類指定特殊的運行器
@RunWith(Parameterized.class)
public class PrimeNumberCheckTest {

    //步驟二:爲測試類聲明幾個變量,分別用於存放指望值和測試所用數據。
    private Integer inputNumber;
    private Boolean expectedResult;
    private PrimeNumberChecker primeNumberChecker;

    @Before
    public void initialize() {
        primeNumberChecker = new PrimeNumberChecker();
    }

    //步驟三:爲測試類聲明一個帶有參數的公共構造函數,並在其中爲第二個環節中聲明的幾個變量賦值。  
    public PrimeNumberCheckTest(Integer inputNumber, Boolean expectedResult){
        this.inputNumber = inputNumber;
        this.expectedResult = expectedResult;
    }
    
    //步驟四:爲測試類聲明一個使用註解 org.junit.runners.Parameterized.Parameters 修飾的,返回值爲  
    //java.util.Collection 的公共靜態方法,並在此方法中初始化全部須要測試的參數對。
    @Parameterized.Parameters
    public static Collection<Object[]> primberNumbers(){
        return Arrays.asList(new Object[][]{
            {2,true},
            {6,false},
            {19,true},
            {22,false},
            {23,true}
        });
    }
    
    //步驟五:編寫測試方法,使用定義的變量做爲參數進行測試。
    @Test
    public void testPrimeNumberChecker(){
        System.out.println("Paramerized Number is : " + inputNumber);
        assertEquals(expectedResult, primeNumberChecker.validate(inputNumber));
    }
}
相關文章
相關標籤/搜索