junit单元测试框架是以jar包的形式提供的。使用时需要导入。
junit使用规范:
1. 一个类如果需要测试,那么该类就应该对应着一个测试类,测试类的命名规范 : 被测试类的类名+ Test。
2. 一个被测试的方法一般对应着一个测试的方法,测试的方法的命名规范是: test+ 被测试的方法的方法名。
代码示例:
1 //业务类 2 public class Tool { 3 4 public static int getMax(){ 5 int a = 3; 6 int b =5; 7 int max = a>b?a:b; 8 return max; 9 } 10 11 public static int getMin(){ 12 int a = 3; 13 int b = 5; 14 int min = a<b?a:b; 15 return min; 16 } 17 18 } 19 20 //单元测试类 21 public class ToolTest { 22 23 @Test 24 public void testGetMax(){ 25 int max = Tool.getMax(); 26 if(max!=5){ 27 throw new RuntimeException(); 28 }else{ 29 System.out.println("最大值:"+ max); 30 } 31 } 32 33 @Test 34 public void testGetMin(){ 35 int min = Tool.getMin(); 36 if(min!=3){ 37 throw new RuntimeException(); 38 }else{ 39 System.out.println("最小值:"+ min); 40 } 41 } 42 }
在方法名前加入@Test代码这个方法可以进行单元测试。上述规则是junit的理想规定,在实际操作中一般都是直接在业务方法名上一行添加@Test直接进行测试,但是测试完之后必须要把@Test删掉。
junit要注意的细节:
1. 如果使用junit测试一个方法的时候,在junit窗口上显示绿条那么代表测试正确,如果是出现了红条,则代表该方法测试出现了异常不通过。
2. 如果点击方法名、 类名、包名、 工程名运行junit分别测试的是对应的方法,类、 包中的所有类的test方法,工程中的所有test方法。
3. @Test测试的方法不能是static修饰与不能带有形参。
4. 如果测试一个方法的时候需要准备测试的环境或者是清理测试的环境,那么可以@Before、 @After 、@BeforeClass、 @AfterClass这四个注解。@Before、 @After 是在每个测试方法测试的时候都会调用一次, @BeforeClass、 @AfterClass是在所有的测试方法测试之前与测试之后调用一次而已。
@Before、 @After、@BeforeClass、 @AfterClass示例代码
1 public class Demo2 { 2 3 //准备测试的环境 4 //@Before 5 @BeforeClass 6 public static void beforeRead(){ 7 System.out.println("准备测试环境成功..."); 8 } 9 10 //读取文件数据,把把文件数据都 11 @Test 12 public void readFile() throws IOException{ 13 FileInputStream fileInputStream = new FileInputStream("F:\a.txt"); 14 int content = fileInputStream.read(); 15 System.out.println("内容:"+content); 16 } 17 18 @Test 19 public void sort(){ 20 System.out.println("读取文件数据排序.."); 21 } 22 23 //清理测试环境的方法 24 // @After 25 @AfterClass 26 public static void afterRead(){ 27 System.out.println("清理测试环境.."); 28 } 29 30 }
断言的常用方法
第一个参数为:expected 期望值
第二个参数为:actual 真实值
Assert.assertSame(5, max); // 底层是使用 ==比较的
Assert.assertSame(new String("abc"), "abc");
Assert.assertEquals(new String("abc"), "abc"); //底层是使用Equals方法比较的
Assert.assertNull("aa");
Assert.assertTrue(true);