资讯专栏INFORMATION COLUMN

JUnit4 note

NicolasHe / 3273人阅读

摘要:步骤三为测试类声明一个带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。步骤五编写测试方法,使用定义的变量作为参数进行测试。

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 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));
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64750.html

相关文章

  • ABAP和Java SpringBoot的单元测试

    摘要:在类里,本地类里用关键字声明过的方法,在单元测试启动后会自动被调用到。在及的设定思路里,放在路径下面以结尾的类会被当成单元测试类处理。 ABAP 在ABAP类里,本地类(Local Class)里用关键字FOR TESTING声明过的方法,showImg(https://segmentfault.com/img/remote/1460000016898407); 在单元测试启动后会自动...

    fireflow 评论0 收藏0
  • junit4备忘录

    摘要:它由和建立,逐渐成为源于的的家族中最为成功的一个。与添加进入的的依赖中。具有两个参数可选该测试方法允许执行的最大时间长度。单位捕获抛出的异常。这个类不包含任何方法更改入口类的测试运行器为将要运行的测试类作为数组传入到中。 简介 JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为...

    TZLLOG 评论0 收藏0
  • springboot整合elasticsearch

    摘要:会把真实值乘以这个因子后存储,取出时再还原。日期类型可以对日期格式化为字符串存储,但是建议我们存储为毫秒值,存储为,节省空间。 最近在学习es,起码要先有个es环境吧,然后再是整合到代码中使用一下,毕竟只有实践才会有深刻的记忆,这就是所谓的经验啊,下面开始吧,本文分两部分,第一部分配置es环境,第二部分整合到springboot中进行简单的操作,本人也是初次学习,如有错误欢迎指出修正,...

    Corwien 评论0 收藏0
  • UnsupportedOperationException

    摘要:本周在写单元测试的时候遇见了一个新的,在此记录一下。通过查看的源码果然是这样没有重写的但为什么会调用方法呢 本周在写单元测试的时候遇见了一个新的exception,在此记录一下。 单元测试中有一段代码是这样的: logger.debug(设置班级的学生); klass.setStudentList(Collections.singletonList(student1)); ...

    LiangJ 评论0 收藏0
  • Spring Boot - 单元测试(Junit4&Mockito)

    摘要:当面讲给你听讲堂地址,或许是最实用的教程,新课促销中,只要你敢来,保你收货满满。优惠报名全程撸码快速入门教程全原价,优惠价全程撸码进阶全原价,优惠价 回顾 Spring Boot - 初识 Hello World Spring Boot - Servlet、过滤器、监听器、拦截器 Spring Boot - 静态资源处理、启动加载、日志处理 Spring Boot - 部署Deplo...

    raoyi 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<