复利计算器的单元测试
2016-03-28 13:07
489 查看
测试说明
各位好, 我想为了方便测试以及考虑到代码的可维护,将复利计算器的计算公式封装到Calculation类中, 静态了其中的方法, 方便调用, 因为对复利相关的计算方法很类似, 所以挑选了Calculation类中的如下方法进行测试:compoundYear() //计算存入年限
simpleMoney() //计算本金
测试是采用junit进行测试, 需要导入junit以及hamcrest的jar包
测试
首先对compoundYear()进行测试, 下面是方法以及测试代码 :compoundYear() :
public static int compoundYear(double compoundMoney, double compoundRate, double compoundSum) { return (int)((Math.log(compoundSum)/Math.log(1+compoundRate))-(Math.log(compoundMoney)/Math.log(1+compoundRate))); }
testCompoundYear() :
@Test public void testCompoundYear() { int compoundYear = Calculation.compoundYear(1000000, 0.1, 2000000); assertThat(compoundYear, is(7)); }
如上所示, 我期待的返回值是7, 采用assertThat()方法进行判断, 结果测试通过 :
其次, 对simpleMoney()进行测试, 下面是方法以及测试代码 :
simpleMoney() :
public static double simpleMoney(double simpleSum, int simpleYear, double simpleRate) { return simpleSum/(1 + simpleYear * simpleRate); }
testSimpleMoney() :
@Test(expected=java.lang.ArithmeticException.class) public void testSimpleMoney() { Calculation.simpleMoney(100000, 1, -1); }
测试这个方法是因为可能会出现除零错误, 通过annotation中的expected测试, 如果出现ArithmeticException, 则表示测试通过 :
本来应该出现除零错误, 但是却报红条! 之后查到是由于计算的时候, 设置的参数都是double类型, 存在精度问题, (double)0 是无限接近于零但是不等于零的, 所以计算除法的时候得到的是无限大的值, 因此报不出除零的Exception
最后通过Grey老师的帮助, 使用BigDecimal类(有兴趣的同学的可以查看一下api文档), 对数据进行处理, 使用了类中的divide()方法, 当无法表示准确的商值时(因为有无穷的十进制扩展),它可以则抛出 ArithmeticException
之后改进的simpleMoney()方法如下:
public static double simpleMoney(double simpleSum, int simpleYear, double simpleRate) { BigDecimal BSimpleSum = new BigDecimal(simpleSum); BigDecimal BSimpleYR = new BigDecimal(1 + simpleYear * simpleRate); return BSimpleSum.divide(BSimpleYR).doubleValue(); }
再次测试 :
以上就是这次测试的内容以及遇到的主要问题啦, 心得就是, 动手做总是能发现未知的问题...
相关文章推荐
- cocos2d-x触摸事件优先级的探究与实践
- code monkey的进化之路
- linux kernel阅读(一) 进程的生命周期
- struts中的helloword(1)
- 网易实习笔试真题C/C++
- Ubuntu 14.04 LTS 64位安装Oracle 11g (二)
- TableTools导出的文件csv都是中文乱码解决办法
- codeforces 25 E Test KMP
- 两个APP共享AccountManager管理的账号
- RotateImageView 旋转的ImageView
- 字体变大变小
- 彻底关闭Pycharm拼写检查
- 建议
- 进制转换
- Android的快速入门(66期第一天)
- webvr技术之three.js
- java 继承多个接口
- 不用一句java代码就可以实现指示器tabhost,indicator
- 大数据并发问题
- Object-C 中 的重要类型