# （三）JUnit 编写单元测试




#### 编写单元测试
---

创建 JunitDemo 类，编写第一个单元测试用例。

```Java
import static org.junit.Assert.assertEquals;
import org.junit.Test;


public class JunitDemo {

    @Test
    public void myFirstTest() {
        assertEquals(2+2, 4);
    }

}
```
__@Test__ 用来注释一个普通的方法为一条测试用例。

__assertEquals()__ 方法用于断言两个值是否相关。

#### 测试功能模块
---

创建一个被测试类：Count ，代码如下：

```Java
public class Count {

    /**
     * 计算并返回两个参数的和
     */
    public int add(int x ,int y){
        return x + y;
    }
}
```
Count 类的实现非常简单，看注释就可以了。

接下来，创建 CountTest 类，用于测试 Count 类。

```Java
import static org.junit.Assert.assertEquals;
import org.junit.Test;


public class CountTest {

    @Test
    public void testAdd() {
        Count count = new Count();
        int result = count.add(2,2);
        assertEquals(result, 4);
    }

}
```
__new__ 出 Count 类，调用 add() 方法并传参，通过 assertEquals() 断言 返回结果。

恭喜！ 你已经会编写单元测试了。




原始封面

![课程图片](https://images.unsplash.com/photo-1581092333322-31d2fd38a35e?w=300)


