欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

搞定Java单元测试,让你的代码更靠谱!

最编程 2024-08-05 19:12:57
...

通过单元测试,能更好的控制代码质量,提升代码质量,及时准确地定位bug;

在java中,JUit是最常用的单元测试工具,我们简单介绍一下他的使用:

测试类的基础结构:

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

public class MyTest {

    @Test
    public void testAddition() {
        int result = Calculator.add(2, 3);
        assertEquals(5, result);
    }

    @Test
    public void testDivision() {
        double result = Calculator.divide(6, 2);
        assertEquals(3.0, result, 0.001);
    }
}

常见的注解有@Test@Before@After@BeforeClass@AfterClass

import org.junit.Before;
import org.junit.Test;

public class MyTest {

    @Before
    public void setUp() {
        // 在每个测试方法运行前执行
    }

    @Test
    public void testSomething() {
        // 测试方法
    }
}

通过断言,我们能初步预期执行结果

import static org.junit.Assert.*;

public class MyTest {

    @Test
    public void testAddition() {
        int result = Calculator.add(2, 3);
        assertEquals(5, result);
    }

    @Test
    public void testNotNull() {
        Object obj = new Object();
        assertNotNull(obj);
    }
}

参数化测试

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

public class ParameterizedTestExample {

    @ParameterizedTest
    @CsvSource({ "1, 2, 3", "0, 0, 0", "-1, 1, 0" })
    void testAddition(int a, int b, int result) {
        assertEquals(result, Calculator.add(a, b));
    }
}