import org.junit.Test;
import static org.junit.Assert.*;
public class MathTest {
@Test
public void testFactorial() throws Exception {
assertEquals(120, new Math().factorial(5));
}
}
java -cp ... org.junit.runner.JUnitCore MathTest
Keeps the bar green to keep the code clean
org.junit.Test
和org.junit.Assert.*
,后者是静态导入testFactorial
是在要测试的方法名factorial
前加个test
@Test
这个注解assertEquals
的作用是判断两个参数是否相等assertXX
方法,这些assertXX
统称为断言@Test
:把一个方法标记为测试方法@Before
:每一个测试方法执行前自动调用一次@After
:每一个测试方法执行完自动调用一次@BeforeClass
:所有测试方法执行前执行一次,在测试类还没有实例化就已经被加载,所以用static
修饰@AfterClass
:所有测试方法执行完执行一次,在测试类还没有实例化就已经被加载,所以用static
修饰@Ignore
:暂不执行该测试方法public class AnnotationTest {
public AnnotationTest() {
System.out.println("构造方法");
}
@BeforeClass
public static void setUpBeforeClass() {
System.out.println("BeforeClass");
}
@AfterClass
public static void tearDownAfterClass() {
System.out.println("AfterClass");
}
@Before
public void setUp() {
System.out.println("Before");
}
@After
public void tearDown() {
System.out.println("After");
}
@Test
public void test1() {
System.out.println("test1");
}
@Test
public void test2() {
System.out.println("test2");
}
@Ignore
public void test3() {
System.out.println("test3");
}
}
@BeforeClass
和@AfterClass
在类被实例化前(构造方法执行前)就被调用了,而且只执行一次,通常用来初始化和关闭资源@Before
和@After
和在每个@Test
执行前后都会被执行一次@Test
标记一个方法为测试方法,被@Ignore
标记的测试方法不会被执行excepted
用来测试异常的timeout
用来测试性能的public class Math {
/**
* 阶乘
* @param n
* @return
*/
public int factorial(int n) throws Exception {
if (n < 0) {
throw new Exception("负数没有阶乘");
} else if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
excepted
测试异常@Test(expected = Exception.class)
public void testFactorialException() throws Exception {
new Math().factorial(-1);
fail("factorial参数为负数没有抛出异常");
}
测试方法会检查是否抛出Exception
异常(当然也可以检测是否抛出其它异常)。如果抛出了异常那么测试通过(因为你的预期就是传进负数会抛出异常)。没有抛出异常则测试不通过执行fail("factorial参数为负数没有抛出异常")
。
public class Sort {
public void sort(int[] arr) {
//冒泡排序
for (int i = 0; i < arr.length - 1; i++) { //控制比较轮数
for (int j = 0; j < arr.length - i - 1; j++) { //控制每轮的两两比较次数
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
timeout
来测试性能public class SortTest {
@Test(timeout = 2000)
public void testSort() throws Exception {
int[] arr = new int[50000]; //数组长度为50000
int arrLength = arr.length;
//随机生成数组元素
Random r = new Random();
for (int i = 0; i < arrLength; i++) {
arr[i] = r.nextInt(arrLength);
}
new Sort().sort(arr);
}
}