Featured image of post Java工程师 测试 junit单元测试使用规范

Java工程师 测试 junit单元测试使用规范

🌏Java工程师 测试 junit单元测试 🎯这篇文章用于记录 使用junit对后端开发进行单元测试(注意测试路径是否覆盖全)

🎄junit单元测试使用规范

编写被测试类

package bbm.com.service.impl;

/**
@author Liu Xianmeng
@createTime 2023/10/23 23:18
@instruction
*/
public class Calculations {
    public int add(int num1, int num2) {
        return num1 + num2;
    }
    public int sub(int num1, int num2) {
        return num1 - num2;
    }
}

编写测试类使用junit测试

注意注释中阐述的junit的使用规范

package bbm.com.service.impl;

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

/**
@author Liu Xianmeng
@createTime 2023/10/23 23:21
@instruction junit测试的使用
            (1)采用断言来进行测试 只有当计算的结果和预估的结果不同的时候 消息会提示错误
            (2)@Before修饰的方法会在所有的测试方法执行前执行 @Before修饰的方法可以有多个 但没必要
            (3)@After修饰的方法会在所有的测试方法执行后执行 @After修饰的方法可以有多个 但没必要
            (4)测试的方法的执行不能修改原数据(txt文件等资源文件)如果测试是删除操作 则可以在@Before和@After方法中进行备份和还原
*/
public class CalculationsTest {
    @Before
    public void before() {
        System.out.println("C CalculationsTest M before()..");
    }
    //@Before
    //public void before2() {
    //    System.out.println("C CalculationsTest M before2()..");
    //}

    @Test
    public void testAdd() {
        Calculations calculations = new Calculations();
        /**
         * 1 参数1 预期和实际的结果不一致的时候提示的错误内容
         * 2 参数2 预期的函数的计算的结果(测试的对象)
         * 3 参数3 实际的(应该是)正确的结果
         *
         * 1 message – the identifying message for the AssertionError (null okay)
         * 2 expected – long expected value.
         * 3 actual – long actual value
         */
        System.out.println("C CalculationsTest M testAdd() -> 测试执行中..");
        Assert.assertEquals("add方法逻辑不正确", calculations.add(10, 2), 12);
    }

    @Test
    public void testSub() {
        Calculations calculations = new Calculations();
        Assert.assertEquals("sub方法逻辑不正确", calculations.sub(10, 2), 8);
    }

    @After
    public void after() {
        System.out.println("C CalculationsTest M after()..");
    }
}
Licensed under CC BY-NC-SA 4.0