# JUnit4的配置和基本使用

 ##配置

### 1.从网上下载jar包,导入Eclipse中

- 从maven仓库中下载,官网https://mvnrepository.com/artifact/junit/junit
- 导入Eclipse中,导入流程 右键项目-----Build Path----Configure Build Path---Libraries---Classpath---Add External JARs--对应相应的jar包---Apply

### 2.eclipse自动导入

- 直接在方法上引用注册@Test,选择第二个Add Junit4 library.....

## 使用

首先新建一个计算机类里面有加减乘除四个方法

代码如下

```java
package work;

public class Counter {
//执行加的方法
public int add(int a,int b) {
return a+b;
}
//执行减的方法
public int subtract(int a,int b) {
return a-b;
}
//执行乘的方法
public int ride(int a,int b) {
return a*b;
}
//执行除的方法
//执行try...catch代码块,如果除数是0则返回值是0,并且给出提示
public int division(int a,int b) {
try {
return a/b;
} catch (Exception e) {
System.out.println("被除数不能为0");
return 0;
}
}
}

```

使用测试类进行测试

```java
package work;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
@SuppressWarnings("all")
public class CounterrTest {
/**
* 调用JUnit中的@Test注释用来调用方法
* 同时使用assertThat中equalTo断言来判断是否和预想值一致
* 画删除线表示过时的方法 将来会被取消 这里我们可以调用assertEquals()方法可以解决这个问题
*/
@Test
public void testAdd() {
assertThat(3, equalTo(new Counter().add(1, 2)));
//预想结果是3,实际返回结果也是3,这个测试为正确
assertEquals(3, new Counter().add(1, 2));
}
@Test
public void testSubtract() {
assertThat(3, equalTo(new Counter().subtract(5, 2)));
assertEquals(3, new Counter().subtract(5, 2));
}
@Test
public void testRide() {
assertThat(6, equalTo(new Counter().ride(2, 3)));
assertEquals(6, new Counter().ride(2, 3));
}
@Test
public void testdivision() {
assertThat(3, equalTo(new Counter().division(6, 2)));
assertEquals(2, new Counter().division(6, 3));
}
}

```

当预想结果和测试结果一致时
[![dG8ob.md.png](https://i.328888.xyz/2023/03/06/dG8ob.md.png)](https://imgloc.com/i/dG8ob)
当预想结果和测试结果不一样时
[![dGNVq.md.png](https://i.328888.xyz/2023/03/06/dGNVq.md.png)](https://imgloc.com/i/dGNVq)

posted @ 2023-03-06 16:26  212409  阅读(128)  评论(0)    收藏  举报