[英]How Can I Write a Proper JUnit Test for this code?
我是编程新手。 我必须为此程序编写一个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);
}
}
我缺少任何可以帮助改进代码的方法吗?
您需要像正常代码中一样实际调用您的方法。 (以下代码未经测试,我不知道1和1是否实际上是互质的。)
public class CoPrimetest {
@Test
public void testing() {
CoprimeNumbersTest instance = new CoprimeNumbersTest();
boolean result = instance.isCoprime( 1, 1 );
boolean expected = true;
assertEquals( expected, result );
}
}
针对您的CoprimeNumbersTest
类中的isCoprime
方法编写的示例测试方法可能是
@org.junit.Test
public void isCoprime() throws Exception {
org.junit.Assert.assertEquals(true, new CoprimeNumbersTest().isCoprime(3,4));
}
由于method的返回类型为boolean
,因此可以断言它等于true
还是false
。
建议,尝试使用这些输入(3,4)
试运行isCoprime
方法,并找出所有已覆盖的语句。 根据该推断,如果您愿意提供什么输入,则将覆盖其余的语句。 这应该有助于用单元测试覆盖代码。
附带说明一下,尝试重命名您的类以练习更好的命名约定,例如GreatestCommonDivisor.java
和GreatestCommonDivisorTest.java
也会将它们链接在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.