单元测试之计算类

单元测试

201421123056 ;201421123057
coding

题目描述:
上一周大家为四则运算程序设计了2-3个新功能,本次在隔了一周之后,我们循序渐进地进阶。本次目标:
把计算模块提取出来,单独创建一个类。
针对提取出来的计算类的接口函数做单元测试。

a.需求分析:测试上有哪些详细的需求?
测试加法是否能正确工作;
测试加减乘除功能;
测试计算类对于各种题目格式的支持。

b. 设计测试框架, 模拟测试数据:
(1) 请给出计算模块的测试用例及运行结果

public class UnitTest1
    {
        [TestMethod]
        public void TestArgException()
        {
            MyMath.FigureUp("1++2");
            MyMath.FigureUp("10000+32768");
            MyMath.FigureUp("248÷0");
               
        }

        [TestMethod]
        public void TestAdd()
        {
            MyMath.FigureUp("1+2");
            MyMath.FigureUp("1+321");
            if(MyMath.FigureUp("232+675") != "907") throw new Exception(); 
        }
        [TestMethod]
        public void TestArithmetic()
        {
            if (MyMath.FigureUp("10+27") != "37") throw new Exception();
            if (MyMath.FigureUp("13-321") != "-308") throw new Exception();
            if (MyMath.FigureUp("232*675") != "156600") throw new Exception();
            if (MyMath.FigureUp("675÷232") != "675/232") throw new Exception();
        }
    }
}

(2) 描述测试过程中遇到的问题以及解决的方案。
调用计算函数时因为函数定义的时候不规范,导致测试时不知是他通过返回的值还是函数内部直接抛出异常来说明调用错误。
解决方法:明确规定调用函数出现错误时以何种方式提示调用者。
(3) 请展示上面描述的单元测试的每个环节。
通过单元测试代码,测试加法是否能正确工作;

[TestMethod]
        public void TestAdd()
        {
            MyMath.FigureUp("1+2+1");
            MyMath.FigureUp("1+321+3");
            if(MyMath.FigureUp("232+675+10") != "917") throw new Exception(); 
        }

通过单元测试代码,测试加减乘除功能。

[TestMethod]
        public void TestArithmetic()
        {
            if (MyMath.FigureUp("10+270+10") != "290") throw new Exception();
            if (MyMath.FigureUp("13-321+8") != "-300") throw new Exception();
            if (MyMath.FigureUp("1+232*675") != "156601") throw new Exception();
            if (MyMath.FigureUp("675÷232") != "675/232") throw new Exception();
        }

通过单元测试代码,测试计算类对于各种参数的支持:
a.输入是有错误的,例如 “1 ++ 2”,
此时抛出异常
b. 在数值范围是 -1000 .. 1000 的时候,传进去 “10000 + 32768”,
此时抛出异常
c. 或者是 “ 248 / 0” 怎么办?
此时抛出异常

 [TestMethod]
        public void TestArgException()
        {
            MyMath.FigureUp("1++2");
            MyMath.FigureUp("10000+32768");
            MyMath.FigureUp("248÷0");
               
        }

d. 怎么告诉函数的调用者 “你错了”? 把返回的字符串定义为 “-1” 来表示?
通过函数抛出的异常来提示调用者出错了
e. 那么如果真的计算结果是 “-1” 又怎么处理呢?
可以通过返回“false”来提示调用出错,其他返回正常的结算结果
c. 小结与感受:通过测试,是否有效发现了程序计算模块的问题,并给予改进?
本来计算模块是放在题目类里,题目类有特殊的数据结构能够更方便地计算结果。
抽出类后要加入字符串的处理,包括题目异常和题目的解析。从这两方面来说是增加了问题但多了字符串的处理使程序兼容了外部的字符串输入。
d. 在隔了一周之后再看之前的代码,是否更能体会到下面这些东西
(1) 良好的设计

(2) 编码规范

(3) 必要的注释
两个好处:
对编程者自己或对将来要改写的人增加可读性
在编写时能够清楚模块的功能和步骤增加编程者自己写代码的效率

原文地址:https://www.cnblogs.com/StayHereForever/p/6640462.html