Idea下Juint 单元测试实践

博客介绍了Java单元测试使用的junit-4.1.jar包,它提供方便强大的接口,省去写main方法的麻烦。还给出junit例子,说明了@before和@after注解的执行时机,且它们是方法级的。同时提到测试方法中若断言结果错误会异常中断,后续方法不执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单元测试用的包:junit-4.1.jar

本质上就是提供了一个方便且功能强大的接口,省去了你写main方法的麻烦。

package JunitPractice;

public class Calculator {
    public int add(int x,int y){
        return x+y;
    }
    public int divide(int x,int y){
        return x/y;
    }
    public static void main(String[] args) {
        int z=new Calculator().add(3, 5);
        System.out.println(z);
    }

}

然后写个junit的例子

package JunitTest;

import JunitPractice.Calculator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class CalculatorTest {
    @Before
    public void setUp() throws Exception {
        System.out.println("method called before...");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("method called after...");
    }

    @Test
    public void add() throws Exception {
        Calculator cal=new Calculator();
        int result=cal.add(2,3);
        System.out.println("run here");
        Assert.assertEquals("答案是错的",6,result);
        System.out.println("run end");
    }

    @Test
    public void divide() throws Exception {

    }

}

其中@before是在测试方法前调用的,@after是测试方法后调用的这两个方法不管测试方法是否报错是否发生异常,都会执行。另外,before和after是方法级的,意思是这俩方法会在所有的@Test方法运行时都会执行。

测试方法就是个简单的计算,如果断言结果是错的,就会发生异常中断,assert后面的方法将不会执行。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值