![](http://hi.csdn.net/attachment/201201/30/0_1327917819GVrh.gif)
两个类 :
类 T:
package com.zhbit.junit4;
public class T {
public int add(int x, int y) {
int z=x+y;
return z;
}
public int divide(int x, int y) {
return x/y;
}
}
类User:
package com.zhbit.junit4;
public class User {
public String getName() {
return "叶璇!";
}
}
测试类:
package com.zhbit.junit4.test;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zhbit.junit4.T;
public class TTest {
// beforeclass 在整个测试类之前和之后运行一次
// 加static 原因是 类还没初始化
@BeforeClass
public static void beforeClass() {
System.out.println("beforeClass!");
}
@AfterClass
public static void afterClass() {
System.out.println("afterClass!");
}
// before 和 after 在每个测试方法之前(之后)运行一次
@Before
public void before() {
System.out.println("before!");
}
// 标明这是一个测试类的方法
@Test
public void testAdd() {
int z = new T().add(5, 3);
assertEquals(8, z);
// 你要引入hamcrest中得相关包 lib core两个
// assertThat里面有许多方法,从而可以摒弃掉junit..Assert里面多个别的方法
// assertThat(z, is(8));
}
// expected 可以捕获异常是测试通过
// timeout 在规定的时间内测试要完成,否则 failure
@Test(expected=java.lang.ArithmeticException.class, timeout=0)
public void testDivide() {
// 理解Errors(程序错误) 和 Failures(测试错误) 区别
int z = new T().divide(8, 0);
}
@After
public void after() {
System.out.println("after!");
}
}
多个类测试:
package com.zhbit.junit4.test;
import static org.junit.Assert.*;
import org.junit.Test;
import com.zhbit.junit4.User;
// 测试多个类 右击+ configurations
public class UserTest {
@Test
public void testGetName() {
String str = new User().getName();
assertEquals("叶璇!", str);
}
}