• 复利计算器的单元测试


    测试说明

    各位好, 我想为了方便测试以及考虑到代码的可维护,将复利计算器的计算公式封装到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()方法进行判断, 结果测试通过 :

    compoundYear测试结果

    其次, 对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, 则表示测试通过 :

    simpleMoney测试结果1

    本来应该出现除零错误, 但是却报红条! 之后查到是由于计算的时候, 设置的参数都是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();
        }
    

    再次测试 :

    simpleMoney测试结果2

    以上就是这次测试的内容以及遇到的主要问题啦, 心得就是, 动手做总是能发现未知的问题...

  • 相关阅读:
    spark 系列之六 SparkStreaming数据源之socket流
    spark 系列之五 SparkStreaming数据源之文件流
    spark 系列之四 Spark数据源之关系型数据库
    spark 系列之三 RDD,DataFrame与DataSet之间的转化
    spark 系列之二 Dataframe的使用
    spark 系列之一 RDD的使用
    Java Int类型与字符,汉字之间的转换
    Java实现栈
    名字的漂亮度
    在字符串中找出连续最长的数字串
  • 原文地址:https://www.cnblogs.com/peivxuan/p/5328649.html
Copyright © 2020-2023  润新知