每天20分钟之简单的单元测试

2022-12-04 22:53:34 浏览数 (3)

简单的单元测试

使用junit和hamcrest

定义要测试的类

代码语言:txt复制
@Builder
@Data
public class AddClass {

    private double a;
    private double b;


    public double add(double a, double b) {
        return a   b;
    }


    public double sub(double a, double b) {
        if (b == 0) {
            throw new IllegalArgumentException("b is zero.");
        }
        return a / b;
    }
}

测试类

  • @before 用于初始化前定义
  • @after用于初始化后定义
  • @Test(expected= IllegalArgumentException.class) 测试异常的情况
代码语言:txt复制
public class AddClassTest   {

    private AddClass addClass = null;


    @Before
    public void setUp() throws Exception {
       addClass = AddClass.builder().build();
    }

    @After
    public void tearDown() throws Exception {
        addClass = null;
    }


    @Test
    public void testAdd() {
        assertThat( addClass.add(1f,2f), equalTo(3.0));
    }

    @Test(expected= IllegalArgumentException.class)
    public void testSub1() {
        assertThat( addClass.sub(1f,0f), equalTo(0f));
    }

    @Test
    public void testSub2() {
        assertThat( addClass.sub(1f,2f), equalTo(0.5));
    }
}

0 人点赞