2017-02-02 82 views
0

我是编程新手。我写这个程序,找到GCD一个JUnit测试,如下所示:如何为此代码编写适当的JUnit测试?

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); 
    } 

} 

有没有,我很想念,任何方法可以帮助改善我的代码?

+0

@BrandonIbbotson'公共类CoPrimetest' VS'公共类CoprimeNumbersTest' –

+0

@BrandonIbbotson,似乎他们并不在同一个班 – nullpointer

+0

@丹 - 什么是'GCDFinder',其实'assetEquals(1,GCDFinder.CoprimeNumbersTest); '对我没有意义。另外它的假设是'assertEquals'(r) – nullpointer

回答

3

您需要实际调用您的方法,就像在普通代码中一样。 (下面的代码没有经过测试,我不知道,如果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); 
    } 
} 
+0

谢谢,这个修复修复了一切。 – dabberson567

1

进行了抽样检测方法编写针对您的CoprimeNumbersTestisCoprime方法可以

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

由于方法的返回类型为boolean,您可以声明它等于truefalse

建议您尝试使用这些输入(3,4)的干式运行isCoprime方法,并计算出所有陈述已被涵盖。根据那些推断什么样的投入,如果你会提供将涵盖其余的陈述。这应该有助于用单元测试覆盖代码。


在一个侧面说明,尝试重命名你的类练习更好的命名惯例,像GreatestCommonDivisor.javaGreatestCommonDivisorTest.java连接它们。