简体   繁体   English

如何更正我的GCD功能单元测试

[英]How to correct my unit test for GCD function

I have written a simple GCD function to implement Euclid's algorithm for computing the greatest common divisor gcd(m, n), which is the largest integer k dividing both m and n. 我编写了一个简单的GCD函数,以实现Euclid算法来计算最大公约数gcd(m,n),这是除以m和n的最大整数k。

The function that I wrote successfully compiles: 我成功编写的函数可以编译:

   public static int gcd(int m, int n) {
      if (n == 0) return m;
      return gcd(n, m%n);
   }

However, I run into an error when I write a unit test on GCD: 但是,当我在GCD上编写单元测试时遇到错误:

   @Test public void gcdTest() {
      for (int m = 0; m < 15; m++) {
      for (int n = 0; n < 15; n++) {
         assertEquals("Divide m,n", m/n%m, Recursion.gcd(m,n));
         }
      }
   }

The error comes in the 'assertEquals' line. 错误出现在“ assertEquals”行中。 I am unsure if maybe I am calculating this method incorrectly by writing m / n % m. 我不确定是否可能通过写m / n%m错误地计算了此方法。

Any tips or suggestions? 有任何提示或建议吗? Thanks in advance. 提前致谢。

Besides the "math" thing here - using loops within unit tests is something that you should not do immediately. 除了这里的“数学”之外,您不应该立即在单元测试中使用循环。

What I mean is: before you think about testcases that iterate and do multiple asserts within a loop, do things like 我的意思是:在考虑在一个循环中迭代并执行多个断言的测试用例之前,请先执行以下操作

@Test
public void gcdTest1_1() {
   assertThat(Recursion.gcd(1,1), is(1));
}

In other words: write simple testcases that test one thing only. 换句话说:编写仅测试件事的简单测试用例。 And when the first one passes, write the next one. 当第一个通过时,写下下一个。 And then, when you are more confident, then consider such looping solution. 然后,当您更有信心时,请考虑使用这种循环解决方案。

As that would might have given you that idea about dividing by 0 ... not being a thing to have in your tests! 这样一来,您可能会想到除以0 ...并不是测试中不可缺少的东西!

Edit upon your comment: use see, the core idea of unit tests is that they help you find and fix bugs in your code under test. 根据您的评论进行编辑:使用see,单元测试的核心思想是它们可以帮助您发现并修复被测代码中的错误。 So looking at your example, the one big obstacle there is ... you are printing a string "m, n". 因此,从您的示例来看,最大的障碍是...您正在打印字符串“ m,n”。 That doesn't tell you anything. 那什么都没告诉你。 You already know that your variables are called m and n. 您已经知道您的变量称为m和n。 You better print the values of m and n in case the assert fails. 最好在断言失败的情况下打印m和n的

Finally: I changed to assertThat ; 最后:我更改为assertThat some other style of assert, that I find to lead to "more readable" code. 我发现其他一些断言风格会导致“更具可读性”的代码。 When using that, you will have to use hamcrest matchers such as is() though (google is your friend here). 使用该功能时,您将不得不使用is()之类的hamcrest匹配器(google是您的朋友)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM