JUnit4 note

java 5 2016-02-29 13:03
女装

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 code

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:

  • Assert which contain a set of assert methods.

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

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

示例代码

最纯净的例子

// 测试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));
    }
}
女装
文章评论