Juint 3.8之菜鸟简记(一)
一,Junit 最佳实践;
- 新建一个名为test 的source folder ,用来存放测试类源代码,建个包,名字和测试对象名字一致
- 目标类编译后class与测试类编译后应该位于同一个包下面,这样测试类就必要导入源代码所在的包,因为他们的class位于同一个包下;
- 测试类的命名规则:在对应测试类后面加上Test
二,Junit 3.8 中,测试方法需要满足如下原则;
- public 的
- void的
- 无方法参数
- 方法名称必须已test开头
源代码:
1 package com.study.junit; 2 3 public class MyStack 4 { 5 private String[] elements; 6 7 private int nexIndex; 8 9 public MyStack() 10 { 11 elements = new String[100]; 12 nexIndex = 0; 13 } 14 15 public void push(String element) throws Exception 16 { 17 if(100 == nexIndex) 18 { 19 throw new Exception("数组越界异常"); 20 } 21 elements[nexIndex++] = element; 22 } 23 24 public String pop() throws Exception 25 { 26 if(0 == nexIndex) 27 { 28 throw new Exception("数组越界异常"); 29 } 30 return elements[--nexIndex]; 31 } 32 33 public void delete(int n) throws Exception 34 { 35 if(nexIndex- n < 0 ) 36 { 37 throw new Exception("数组越界异常"); 38 } 39 40 nexIndex -= n; 41 } 42 43 44 public String top() throws Exception 45 { 46 if(0 == nexIndex ) 47 { 48 throw new Exception("数组越界异常"); 49 } 50 51 return elements[nexIndex - 1]; 52 53 } 54 55 }
测试代码:
1 package com.study.junit; 2 3 import junit.framework.TestCase; 4 5 /* 简单设计2个testcase,其他testcase省略; 6 * 1,push一个数据,pop 一个数据; 7 * 2,Push101个数据; 8 * 9 */ 10 11 public class testMyStack extends TestCase 12 { 13 private MyStack mystack; 14 15 @Override 16 public void setUp() throws Exception { 17 18 mystack = new MyStack(); 19 } 20 21 public void testpush1() 22 { 23 try { 24 mystack.push("helloworld"); 25 26 } catch (Exception e) { 27 fail("测试失败"); 28 } 29 30 String result = null; 31 32 try { 33 result = mystack.pop(); 34 } catch (Exception e) { 35 fail("测试失败"); 36 } 37 38 assertEquals("helloworld",result); 39 } 40 41 //testcase2:Push101个数据; 42 public void testpush2() 43 { 44 Throwable tx = null ; 45 46 try { 47 48 for(int i = 0 ; i <= 100 ;i++ ) 49 { 50 mystack.push(i + ""); 51 } 52 53 fail("测试失败"); 54 } catch (Exception e) { 55 tx = e ; 56 } 57 assertNotNull(tx); 58 assertEquals(Exception.class, tx.getClass()); 59 assertEquals("数组越界异常", tx.getMessage()); 60 } 61 62 public static void main(String[] args) { 63 junit.textui.TestRunner.run(testMyStack.class); 64 65 } 66 67 }
run - > java application ; Ok