簡體   English   中英

如何為該代碼編寫正確的JUnit測試?

[英]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.javaGreatestCommonDivisorTest.java也會將它們鏈接在一起。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM