Junit入门

    最近项目组打算规范编码,控制代码质量,引入Unit Test开发方式,

Junit是一个很好的工具,自己写了几个非常简单的例子,希望能让大家

以超快的速度入门,看完就会知道,unit test是一件十分简单有趣的事情.

先写两个功能类:

1.

package com.founder.ws;

public class Compute {
  public static int add(int a,int b){
    return a+b;
  }
}

2.

package com.founder.ws;

public class StringUtil {
  public static String concat(String s1,String s2){
    return s1+s2;
  }
  public static boolean isNull(String s){
    if (s == null) {
      return true;
    }
    return false;
  }
}

为这两个功能类写两个测试用例(Test Case)

1.

package com.founder.ws;

import junit.framework.*;

public class TestCompute extends TestCase {
  private Compute compute = null;

  protected void setUp() throws Exception {
    super.setUp();
    compute = new Compute();
  }

  protected void tearDown() throws Exception {
    compute = null;
    super.tearDown();
  }
  public void testAdd(){
     this.assertEquals("add result is error!",5,compute.add(1,4));
  }

}

2.

package com.founder.ws;

import junit.framework.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class TestStringUtil extends TestCase {
  private StringUtil stringUtil = null;

  protected void setUp() throws Exception {
    super.setUp();
    stringUtil = new StringUtil();
  }

  protected void tearDown() throws Exception {
    stringUtil = null;
    super.tearDown();
  }

  public void testConcat() {
    String s1 = "a";
    String s2 = "b";
    String expectedReturn = "ab";
    String actualReturn = stringUtil.concat(s1, s2);
    assertEquals("return value", expectedReturn, actualReturn);
    /**@todo fill in the test code*/
  }

  public void testIsNull() {
    String s = null;
    boolean expectedReturn = true;
    boolean actualReturn = stringUtil.isNull(s);
    assertEquals("return value", expectedReturn, actualReturn);
    /**@todo fill in the test code*/
  }

}

写一个TestSuite类,把两个Test Case加进来,这样就可以运行这个TestSuite来完成

两个TestCase的运行.

    利用TestSuite可以将一个TestCase子类中所有test***()方法包含进来一起运行,还可将TestSuite子类也包含进来,从而行成了一种等级关系。可以把TestSuite视为一个容器,可以盛放TestCase中的test***()方法,它自己也可以嵌套。这种体系架构,非常类似于现实中程序一步步开发一步步集成的现况。

package com.founder.ws;

import junit.framework.*;

public class AllTests {


  public static Test suite() {
    TestSuite suite = new TestSuite();
    suite.addTestSuite(TestCompute.class);
    suite.addTestSuite(TestStringUtil.class);
    return suite;
  }
}

运行这个Test Suite ,显示出Junit的绿色条,三个方法全部通过,OK,测试通过.

如果出现红色条,按照指示回去功能类里找BUG,修改完毕,重新运行Test Suite,

直到绿色条出现,这便是一个简单的Junit测试过程.简单吧 :)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值