--------------------Mystack.java---------------------------------------
1 package senlin.junit;
2
3 public class Mystack {
4 private String[] elements;
5 private int nextIndex;
6 public Mystack(){
7 elements=new String[100];
8 nextIndex=0;
9
10 }
11 public void push(String element) throws Exception{
12 if(100==nextIndex){
13 throw new Exception("数组越界!");
14 }
15 elements[nextIndex++]=element;
16
17 }
18 public String pop() throws Exception{
19 if(0==nextIndex){
20 throw new Exception("数组越界!");
21 }
22 return elements[--nextIndex];
23 }
24
25
26 public void delete(int n) throws Exception{
27 if(nextIndex-n<0){
28 throw new Exception("数组越界!");
29 }
30 nextIndex-=n;
31 }
32
33 public String top() throws Exception{
34 if(0==nextIndex){
35 throw new Exception("数组越界!");
36 }
37 return elements[nextIndex-1];
38 }
39
40 }
41
1 package senlin.junit;
2
3 import junit.framework.Assert;
4 import junit.framework.TestCase;
5
6 public class MystackTest extends TestCase{
7 private Mystack mystack;
8 public void setUp(){
9 mystack=new Mystack();
10 }
11 //正常情况,压进去一个.再弹出来.看看结果是不是一样的来判断是否正确
12 public void testPush(){
13 try {
14 mystack.push("hellow world"); //任意压进一个合法字符串
15 } catch (Exception e) {
16 Assert.fail(); //如果抛出错误则测试失败
17 }
18 String result=null;
19 try{
20 result=mystack.pop(); //弹出刚才压进去字符串
21 }catch(Exception ex){
22
23 }
24 Assert.assertEquals("hellow world", result); //检查期望结果是否一致
25 }
26
27 //测试左边界100个Index
28 public void testPush2(){
29 //用循环压入100个字符
30 for(int i=0;i<100;i++){
31 try{
32 mystack.push(i+"");
33 }catch(Exception ex){
34 Assert.fail(); //正常情况是不会抛出异常的.如果有异常则测试失败
35 }
36 }
37
38 for(int i=0;i<100;i++){
39 String result=null;
40 try{
41 result=mystack.pop(); //拿到最后弹出的一个字符串
42 }catch(Exception ex){
43
44 }
45 Assert.assertEquals((99-i)+"", result); //最后一个弹出来等于第一个放进去
46 }
47 }
48 //右 边界.index=101的时候测试
49 public void testPush3(){
50 Exception tx=null;
51 try{
52 for(int i=0;i<=100;i++){ //压进101个字符串
53 mystack.push(i+"");
54 }
55 Assert.fail(); //如果能执行到这一步表示没有异常抛出.测试失败
56 }catch(Exception ex){
57 tx=ex; //抛出异常.把异常赋值给tx变量以便操作后续
58 }
59 Assert.assertNotNull(tx); //检查异常是否为空
60 Assert.assertEquals(Exception.class, tx.getClass()); //检查错误类是否一致
61 Assert.assertEquals("数组越界!", tx.getMessage()); //检查预期的结果和抛出异常信息是否一致
62
63 }
64
65
66 }
67
68