你好,游客 登录 注册 搜索
背景:
阅读新闻

在Eclipse外使用JUnit测试

[日期:2013-02-24] 来源:Linux社区  作者:czjuttsw [字体:大 中 小]

Eclipse IDE 集成了JUnit开源单元测试框架。如果不借助Eclipse的图形界面工具来生成并运行我们的JUnit测试,该怎么实现呢?

1. 首先需要在类路径下添加JUnit-4.X jar 包。

2. 编写需要测试的方法。

public class Calculator {

 private Calculator(){}
 
 public static int add(int x, int y) {
  return x + y;  // 正确
 }
 
 public static int subtract(int x,int y) {
  return y - x;  // 错误
 }
 
 public static int multiply(int x, int y) {
  throw new RuntimeException(); // 抛出异常
 }
 
 public static int divide(int x, int y) {
  return x / y;  // divided by 0
 }
 
 public static int module(int x , int y) {
  for(;;); //死循环
 }

}

编写测试类(Test Class)

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.zjut.junit.Calculator.*;

public class CalculatorTest {

 @Before
 public void setUp() throws Exception {
  System.out.println("Before testing");
 }

 @After
 public void tearDown() throws Exception {
  System.out.println("After testing");
 }

 @Test
 public void testAdd() {
  assertEquals("add", 3, add(1, 2));
 }

 @Test
 public void testSubtract() {
  assertEquals("subtract", 3, subtract(5, 2));
 }

 @Test
 public void testMultiply() {
  assertEquals("multiply", 9, multiply(3, 3));
 }

 @Test(expected = ArithmeticException.class)
 public void testDivide() {
  divide(3, 0);
 }

 @Test(timeout=200)
 public void testModule() {
  module(1, 2);
 }

}

linux
相关资讯       Eclipse JUnit  JUnit测试mEclipse 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款