1.常用@标签
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class NormalTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("只执行一次");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("只执行一次");
}
@Before
public void setUp() throws Exception {
System.out.println("每次调用test方法都执行一次");
}
@After
public void tearDown() throws Exception {
System.out.println("每次调用test方法都执行一次");
}
@Test(timeout=1000)
public void testTimeout(){
try {
Thread.sleep(1200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("NormalTest.normalTest()");
}
@Test(expected=Exception.class)
public void testExpectedException() throws Exception{
System.out.println("NormalTest.expectedExceptionTest()");
throw new Exception();
}
}
2.参数化测试
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class ParametersTest {
private String expected;
private String target;
@Parameters
public static Collection words() {
return Arrays.asList(new Object[][] { { "employee_info", "employeeInfo" }, // 测试一般的处理情况
{ null, null }, // 测试 null 时的处理情况
{ "", "" }, // 测试空字符串时的处理情况
{ "employee_info", "EmployeeInfo" }, // 测试当首字母大写时的情况
{ "employee_info_a", "employeeInfoA" }, // 测试当尾字母为大写时的情况
{ "employee_a_info", "employeeAInfo" } // 测试多个相连字母大写时的情况
});
}
/**
* 参数化测试必须的构造函数
*
* @param expected
* 期望的测试结果,对应参数集中的第一个参数
* @param target
* 测试数据,对应参数集中的第二个参数
*/
public ParametersTest(String expected, String target) {
this.expected = expected;
this.target = target;
}
/**
* 测试将 Java 对象名称到数据库名称的转换
*/
@Test
public void wordFormat4DB() {
assertEquals(expected, target);
}
}
3.测试套件TestSuite
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ NormalTest.class })
public class AllTests {
/*public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
// $JUnit-BEGIN$
suite.addTestSuite(NormalTest.class);//添加测试的类 ,必须是TestCase的子类
// $JUnit-END$
return suite;
}*/
}