zoukankan      html  css  js  c++  java
  • Junit4单元测试

    视频地址

    步骤

    • 1.在工程目录下新建一个source folder命名为test专门存放测试类
      • 在工程上,右键->new->Source Folder
    • 2.为需要创建测试类的创建测试类
      • 在类文件上,右键->new->JUnit Test Case
      • 把目录为新建的test目录,包名要与被测试类相同
      • 可以勾选是否自动生成@BeforeClass;@AfterClass;@Before;@After;注解方法
      • 点击,next可以选择需要测试的方法
    • 3.运行测试类里的一个方法
      • 将光标选中该方法,右键->Run As->JUnit Test
    • 4.运行测试类里所有方法
      • 将光标移出方法名的范围,右键->Run As->JUnit Test
    • 5.运行多个测试类里的所有方法
      • a.新建一个测试类,
      • b.删除新建类的所有方法
      • c.用@RunWith(Suite.class)注解将runner改为Suite
      • d.用@Suite.SuiteClasses()以数组的方式设置要跑的多个测试类
    package com.ztc;
    import static org.junit.Assert.*;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    @RunWith(Suite.class)
    @Suite.SuiteClasses({CalculateTest.class,TaskTest.class})
    public class SuiteTest {
    }
    • 6.运行多组参数测试
      • a.更改默认的测试运行器为RunWith(Parameterized.class)
      • b.声明变量存放预期值和测试数据
      • c.声明一个返回值 为Collection的公共静态方法,并使用@Parameters进行修饰
      • d.为测试类声明一个带有参数的公共构造函数,并在其中为之声明变量赋值
      • e.运行测试方法,即可完成对多组数据的测试
    package com.ztc;
    
    import static org.junit.Assert.*;
    
    import java.util.Arrays;
    import java.util.Collection;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.Parameterized;
    import org.junit.runners.Parameterized.Parameters;
    
    @RunWith(Parameterized.class) 
    public class ParamersTest {
    
        int ans;
        int a;
        int b;
    
    
        public ParamersTest(int ans, int a, int b) {
            this.ans = ans;
            this.a = a;
            this.b = b;
        }
        @Parameters
        public static Collection<Object[]> t() {  
            return Arrays.asList(new Object[][]{  
                    {4,1,2},  
                    {4,2,2},
                    {3,1,2}
            }) ;  
        }  
        @Test
        public void testAdd() {
            assertEquals(ans, new Calculate().add(a, b));
        }
    }
    

    常见注解

    • @Test:将一个普通的方法修饰成为一个测试方法
      • @Test(expected=XX.class)
      • @Test(timeout=毫秒)
    • @BeforeClass:它会在所有的方法运行前被执行,static修饰
    • @AfterClass:它会在所有的方法运行结束后被执行,static修饰
    • @Before:会在每一个测试方法被运行前执行一次
    • @After:会在每一个测试方法运行后被执行一次
    • @Ignore:所修饰的测试方法会被测试运行器忽略
    • @RunWith:可以更改测试运行器 org.junit.runner.Runner

    Test执行流程

    [@BeforeClass]->{ ([@Before]->[@Test]->[@After]) … }->[@AfterClass]

  • 相关阅读:
    java selenium (十) 操作浏览器
    java selenium (九) 常见web UI 元素操作 及API使用
    java selenium (六) XPath 定位
    正则表达式
    日志模板
    软件开发规范
    TCP协议的粘包现象和解决方法
    验证用户的合法性
    PythonDay16
    PythonDay15
  • 原文地址:https://www.cnblogs.com/A-yes/p/9894188.html
Copyright © 2011-2022 走看看