java之 junit单元测试案例【经典版】

目录

一  junit单元测试

1.1 单元测试作用

1.2 案例1 常规单元测试

1.3 案例2 单元覆盖率Coverage*

1.4 案例3 BeforeEach,BeforeAfterall

1.4.1 Api说明

1.4.2 案例操作 

1.5 案例4  junit+反射+注解实现测试

1.6 案例5  web工程单元测试

1.6.1 mock和spy的区别联系

1.6.2 案例


一  junit单元测试

1.1 单元测试作用

单元测试要满足AIR原则,即

A: automatic 自动化;

I: Independent  独立性;

R:Repeatable 可重复;

2.单元测试必须使用assert来验证

1.2 案例1 常规单元测试

1.代码

public class CalcDemo
{
    public int add(int x ,int y)
    {
        return x + y;
        //return x * y;
    }

    public int sub(int x ,int y)
    {
        return x - y;
    }
}

2.测试

public class AppTest 

{
    @Test
    void sub()
    {
        CalcDemo calcDemo = new CalcDemo();
        int retValue = calcDemo.sub(2, 2);
        assertEquals(0,retValue);
        System.out.println("");
    }
}

1.3 案例2 单元覆盖率Coverage*

1.代码

public class ScoreDemo
{
    public String scoreLevel(int score)
    {
        if(score <= 0) {
            throw new IllegalArgumentException("缺考");
        } else if (score < 60) {
            return "弱";
        } else if (score < 70) {
            return "差";
        } else if (score <= 80) {
            return "中";
        } else if (score < 90) {
            return "良";
        } else {
            return "优";
        }
    }
}

2.测试

class ScoreDemoTest
{
    @Test
    void scoreLevel()
    {
        ScoreDemo scoreDemo = new ScoreDemo();
        assertEquals("弱",scoreDemo.scoreLevel(52));
    }

    @Test
    void scoreLevelv2()
    {
        ScoreDemo scoreDemo = new ScoreDemo();
        assertEquals("差",scoreDemo.scoreLevel(62));
    }

    @Test
    void scoreLevelv3()
    {
        ScoreDemo scoreDemo = new ScoreDemo();
        assertEquals("中",scoreDemo.scoreLevel(80));
    }

    @Test
    void scoreLevelv4()
    {
        ScoreDemo scoreDemo = new ScoreDemo();
        assertThrows(IllegalArgumentException.class,() -> scoreDemo.scoreLevel(-7));
    }
}

查看测试报告:对应覆盖率

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值