问题
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;
}
}
}
This is what I could come up with:
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:
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 );
}
}
回答2:
A sample test method to write against the isCoprime
method in your CoprimeNumbersTest
class could be
@org.junit.Test
public void isCoprime() throws Exception {
org.junit.Assert.assertEquals(true, new CoprimeNumbersTest().isCoprime(3,4));
}
Since the return type of method is boolean
, you can either assert it equal to either true
or false
.
Would suggest, try to dry run isCoprime
method with these inputs (3,4)
and figure out what all statements have been covered. Based on the that infer what inputs if you would provide would cover the remaining of the statements. That should help to cover the code with Unit Tests.
On a side note, try renaming your classes to practice a better naming convention, something like GreatestCommonDivisor.java
and GreatestCommonDivisorTest.java
linking them as well.
来源:https://stackoverflow.com/questions/41993286/how-can-i-write-a-proper-junit-test-for-this-code