如何为该代码编写正确的JUnit测试? [英] How Can I Write a Proper JUnit Test for this code?
本文介绍了如何为该代码编写正确的JUnit测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是编程新手.我必须为此程序编写一个JUnit测试才能找到GCD,如下所示:
I'm new to programming. I have to write a JUnit test for this program to find the GCD, shown here :
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);
}
}
我缺少任何有助于改善代码的方法吗?
Are there any approaches that I am missing that can help to improve my code?
推荐答案
您需要像正常代码中一样实际调用您的方法. (以下代码未经测试,我不知道1和1是否实际上是互质的.)
You need to actually call your method, just like in normal code. (The following code is not tested, I don't know if 1 and 1 are actually co-prime.)
public class CoPrimetest {
@Test
public void testing() {
CoprimeNumbersTest instance = new CoprimeNumbersTest();
boolean result = instance.isCoprime( 1, 1 );
boolean expected = true;
assertEquals( expected, result );
}
}
这篇关于如何为该代码编写正确的JUnit测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文