如何为此代码编写正确的JUnit测试?

时间:2017-02-02 02:29:58

标签: java junit greatest-common-divisor

我是编程新手。我必须为这个程序编写一个JUnit测试来找到GCD,如下所示:

public class CoprimeNumbersTest {


/**
 * Given two integers, this returns true if they are relatively prime and  false if they are not. Based upon the first
 * webpage I found ({@link "https://primes.utm.edu/notes/faq/negative_primes.html"}), the primality of negative
 * numbers is up for debate. This method will not treat negatives differently.
 *
 * @param a First integer to be tested
 * @param b Second integer to be tested
 * @return True when the greatest common divisor of these numbers is 1; false otherwise.
 */
public boolean isCoprime(int a, int b) {
  // Continue using Euclid's algorithm until we find a common divisor
  while (b != 0) {
// Remember b's value
int temp = b;
// Set b to the remainder of dividing a by b (e.g., a mod b).
b = a % b;
// Set a equal to b's old value.
a = temp;
  }
   // The gcd is the value in a. If this is 1 the numbers are coprime.
   if (a == 1) {
return true;
     }
  // When they are not 1, they have a common divisor.
  else {
return false;
  }
}
}

这是我能想到的:

public class CoPrimetest {

    @Test
    public void testing() { 
        assetEquals(1, GCDFinder.CoprimeNumbersTest);
    }

}

我是否有任何可以帮助改进代码的方法?

2 个答案:

答案 0 :(得分:3)

您需要实际调用您的方法,就像在普通代码中一样。 (以下代码未经过测试,我不知道1和1是否实际上是共同的。)

img

答案 1 :(得分:1)

isCoprime课程中针对CoprimeNumbersTest方法撰写的示例测试方法可以是

@org.junit.Test
public void isCoprime() throws Exception {
    org.junit.Assert.assertEquals(true, new CoprimeNumbersTest().isCoprime(3,4)); 
}

由于方法的返回类型为boolean,因此您可以将其置为等于truefalse

建议,尝试使用这些输入isCoprime来运行(3,4)方法,并找出所有语句都已涵盖的内容。根据推断,如果你提供什么输入将覆盖其余的陈述。这应该有助于用单元测试覆盖代码。

在旁注中,尝试重命名您的类以实践更好的命名约定,例如GreatestCommonDivisor.javaGreatestCommonDivisorTest.java也可以将它们链接起来。