Junit4测试

1.新建maven项目,在pom.xml文件中引入:

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId><version>4.12</version>
            <scope>test</scope></dependency>
    </dependencies>

2.新建类File,编写一个求绝对值的函数,用于测试:

public class File {
    public static int abs(int a){
        int a_abs=0;
        try {
            a_abs=(a>0)?a:-a;
        }catch(Exception e){
            System.out.println("输入格式错误");
        }
        return a_abs;
    }
    public static void main(String[] args){
        System.out.print(abs(-3257));
    }
}

2.在同级目录下新建test文件夹,在test文件夹下新建java,编写测试类FileTest:

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class FileTest {
    @Test
    public void Testabs() throws Exception {

        assertEquals(5, new File().abs(-5));
    }
}

3.文件结构;

4.运行测试文件:

 

5.解释:

第一,导入了org.junit.Test;和org.junit.Assert.*;这两个包,注意后者是静态导入import static。
第二,FileTest是在要测试的方法名Factorial前加个test(这也是个好习惯)。
第三,所有测试方法返回类型必须为void且无参数。
第四,一个测试方法之所以是个测试方法是因为@Test这个注解。
第五,assertEquals的作用是判断两个参数是否相等,例子中5是预期结果,new File().abs(-5)是实际结果。但是通常不应该只比较一个值,要测试多几个特殊值,特别是临界值。

 

posted @ 2022-04-08 19:47  风吹过半夏  阅读(103)  评论(0编辑  收藏  举报