5.3技术补充——JUnit断言测试

JavaWeb学习文章索引点这里
JUnit断言测试注意事项:
1,在eclipse中build path里添加libarry,目前是JUnit5
2,JUnit方法顶部需要加上@Test注解
3,方法必须public void 方法名() 形式,可以抛出异常
4,单独运行一个方法选中方法名,右键点击进行运行
5,运行所有方法选中类名,右键点击进行运行
断言类的一些方法:
断言的方法
断言类使用简单示例:
先准备一个普通运算类,一个自己重写过equals方法的person类
运算类,

package com.math;

public class SimpleMathFunction {

    public int add(int a, int b) {
        return a+b;
    }

    public int mov(int a, int b) {
        return a/b;
    }
}

Person类,

package com.bean;

public class Person {
    private int id;
    String name;

    public Person() {
        super();
    }
    public Person(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object obj) {
        Person person = (Person)obj;
        return this.id == person.id && this.name == person.name;
    }
}

然后调用assert比较方法来判断结果,这里选用的是assertSame和assertEquals方法。assertSame方法相当于是使用==来进行判断,是否相等。assertEquals方法相当于是使用equals方法,根据返回结果来进行判断。
测试类:

package com.test;

import static org.junit.Assert.assertSame;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.Test;
import com.bean.Person;
import com.math.SimpleMathFunction;

public class Junit_Test {
    SimpleMathFunction math = new SimpleMathFunction();

    @Test
    public void testAdd() {
        assertSame(15, math.add(10, 5));
    }

    @Test
    public void testMov() {
        assertEquals(2, math.mov(10, 5));
    }

    @Test
    public void testPerson1() {
        Person person1 = new Person(1,"zhangsan");
        Person person2 = new Person(1,"zhangsan");
        //person2 = person1;
        assertSame(person1, person2);
    }

    @Test
    public void testPerson2() {
        Person person1 = new Person(1,"zhangsan");
        Person person2 = new Person(1,"zhangsan");
        //person1 = person2;
        assertEquals(person1, person2);
    }
}

结果:
结果
使用same的时候判断的是它们是否是同一个对象,测试结果为不通过,使用equals的时候由于我们重写了比较方法,所以测试通过

猜你喜欢

转载自blog.csdn.net/smallhc/article/details/81081109
今日推荐