算法的 Junit 测试

Junit Test for algorithm

我尝试解决这个问题:

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit

这是我写的代码:

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) 我得到了需要的值。 请解释这是怎么可能的?

您不会在两次调用之间将 counter 的状态恢复为 0:

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

您应该查看您的结果并询问 "Why am I not getting what I think I should be getting?"。使用调试器,您会发现在从外部调用 persistance 之前您的计数器没有被重置。 Hello.persistance(39) 将计数器设置为 3,然后 Hello.persistance(4) returns 硬编码值 0。

为每个测试用例创建一个新的 class,这样就没问题了。