单元测试
2016-09-11 00:07 李秀琪 阅读(215) 评论(0) 编辑 收藏 举报1什么是单元测试?
单元测试(junit testing),是指对软件中的最小可测试单元进行检查和验证。Java里单元指一个类。
JUnit ,是一个开源的Java单元测试框架,是 Java的标准单元测试库,是非常重要第三方 Java 库,由 Kent Beck 和 Erich Gamma 开发。
Junit作为一个软件测试的工具,JUnit可以不破坏java原代码,使用方便,添加快捷,代码量少,可视化的测试。
2:JUnit单元测试步骤:
1.导入包junit测试包:JUnit测试版本,3.81版,4.0版,导入对应的jar包;
2.写一个类扩展(继承)TestCase;
3.在需要测试的方法名前加test生成新的测试方法;
4.运行测试,用断言(assert***)的方法测试成功(显示绿色)或失败(显示红色),或者自己判断结果正确与否。
junit类单元测试:
- package com.myhome;
- public class Mul{
- public int mul(int x,int y) {
- public int mul(int x,int y) {
- return x*y;
- }
- public double divide(double x,double y){
- return x/y;
- }
- }
用myeclipse集成开发环境添加jar包和junit测试支持:
1.如果没有就在new菜单最下边Other……中(或Ctrl+N),输入junit选择JUnit Test Case单元测试:
2.选择JUnit 3 Test测试:
3.选择要测试的方法:
4.此时会自动导入jar包(junit3或者junit4需要的jar包),
5.程序目录结构:
6.此时的测试类为:
- package com.myhome.test;
- import junit.framework.TestCase;
- public class MulTest extends TestCase {
- public void testMul() {
- fail("Not yet implemented");
- }
- public void testDivide() {
- fail("Not yet implemented");
- }
- }
测试内部方法体:
- public void testMul() {
- Mul mul = new Mul();
- int res = mul.mul(2, 4);
- System.out.println(res);
- }
- public void testDivide() {
- Mul mul = new Mul();
- double res = mul.divide(8.0, 2.0);
- assertEquals(4.0, res);
- }
效果图: