2017-02-02 81 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連接它們。