有人说我们再java程序中使用main方法一样可以进行测试,但是有以下点不好的地方:
1、单元测试不能一起运行;
2、大部分情况需要人为地观察;
本次junit测试,使用的是maven管理的。所以需要先加入依赖,必须先写hamcrest,再写junit,因为junit内置了一个hamcrest。依赖如下:
<dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency>
然后写需要测试的代码,简单的加减操作,如下:
public class Calc {
public int add(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
}
首先,我们先简单地写一下单元测试,运行单元测试,看能否正常执行
public class CalcTest {
@Test
public void testAdd() {
System.out.println("add...");
}
}
ok,能正常打印出字符串。下面我们加入import包含,测试junit4原始的测试方法
package com.learning.test;
import static junit.framework.Assert.*;
import org.junit.Test;
public class CalcTest {
@Test
public void testAdd() {
assertEquals(5, new Calc().add(1, 4));
}
}
下面我们来测试一下junit4新的测试方法,使用assertThat方法。这儿就需要用到hamcrest,这会更接近我们使用的自然语言
package com.learning.test;
import static junit.framework.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class CalcTest {
@Test
public void testAdd() {
System.out.println("add...");
assertEquals(5, new Calc().add(1, 4));
}
@Test
public void testSub() {
System.out.println("sub...");
assertThat(new Calc().sub(5, 1), greaterThan(3));
assertThat(new Calc().sub(5, 1), lessThan(5));
assertThat(new Calc().sub(5, 1), is(4));
assertThat(new Calc().sub(5, 1), allOf(greaterThan(3), lessThan(5)));
}
}
同时,junit4还引入了格式标签,例如:
@Ignore // 忽略此方法
@Before // 当前类中每个测试方法执行前执行
@After // 当前类中每个测试方法执行后执行
@BeforeClass // 当前类中所有测试方法执行前执行,方法必须是static的
@AfterClass // 当前类中所有测试方法执行后执行,方法必须是static的