Junit测试算法

时间:2015-08-17 11:59:59

标签: java junit

我尝试解决这个问题:

  

写一个函数,持久性,它接受一个正参数num并返回它的乘法持久性,这是你必须乘以num中的数字直到达到一位数的次数

这是我写的代码:

public class Hello {
        static int counter = 0;
        public static int persistence(long n) {
        int digits = digit_count(n);
        if (digits <= 1) {
          return 0;
        }
        persistence(product(n));
        counter++;
        return counter;
        }
      public static int product(long n) {
      int productValue = 1;
        while (n != 0) {
          productValue *= n % 10;
            n /= 10;
         }
        return productValue;
      }

      public static int digit_count(long n) {
        int count = 0;
        while (n > 0) {
          n /= 10;
          count++;
        }
        return count;
      }

和JUnit测试:

assertEquals(3, Hello.persistence(39));
assertEquals(0, Hello.persistence(4));
assertEquals(2, Hello.persistence(25));
assertEquals(4, Hello.persistence(999));

25和999的测试失败,但是如果我尝试在 main 方法中调用Hello.persistence(25)和Hello.persistence(999),我得到了所需的值。 请解释一下这是怎么回事?

2 个答案:

答案 0 :(得分:1)

你应该看看你的结果并询问&#34;为什么我没有得到我认为应该得到的东西?&#34;。使用调试器,您会发现在从外部呼叫persistance之前,您的计数器未被重置。 Hello.persistance(39)将计数器设置为3,然后Hello.persistance(4)返回硬编码值0。

为每个测试用例创建一个新类,你就可以了。

答案 1 :(得分:0)

您没有在调用之间将counter的状态恢复为0:

Hello.persistence(39);
//counter is now equal to 3, furter invocations will add "3" to the result