簡體   English   中英

JUnit測試是否可以通過iff方法實現正確且遞歸的方法?

[英]Is there a way for a JUnit test to pass iff method implementation is correct AND recursive?

我正在設置一些實踐考試,並要求某些方法的實現是遞歸的。 是否只有在方法的實現是遞歸的(當然是正確的)的情況下,JUnit測試才能通過?

我已經嘗試過使用getStackTrace()但是我找不到方法來獲取程序前面的方法調用。 (因為我可以這樣做,所以我可以檢查以下示例中的containsDigit是否被調用了所需的次數)

MWP

import static org.junit.Assert.*;
import org.junit.*;
import java.io.*;
import java.text.*;
import java.util.*;
import org.junit.rules.*;
import java.lang.reflect.*;

public class Service { //begin class 
    /**
     * @param n: assumed to be more than 0
     * @param d, d >= 0 and d <= 9
     * @return true if number n contains the digit d, false otherwise
     * you may assume that 0 itself doesn't contain ANY digit (not even 0)
     * NOTE: This method must be implemented recursively.
     * hint: n%10 gives the last digit, n/10 gives the rest of the number
     */
    public static boolean containsDigit(int n, int d) {
        return false; //to be completed
    }

    @Test
    public void testContainsDigit() {
        assertTrue(Service.containsDigit(1729, 1));
        assertTrue(Service.containsDigit(1234567890, 2));
        assertFalse(Service.containsDigit(1729, 8));
    }
}

我希望測試通過遞歸實現,例如:

    public static boolean containsDigit(int n, int d) {
        if(n == 0) 
            return false;
        if(n%10 == d)
            return true;
        return containsDigit(n/10, d);
    }

並無法進行迭代(即使正確)的實現,例如:

    public static boolean containsDigit(int n, int d) {
        while(n > 0) {
            if(n%10 == d) {
                return true;
            }
            n/=10;
        }
        return false;
    }

任何幫助或正確方向的指導將不勝感激。

JUnit本身沒有工具來檢查流是遞歸的還是迭代的,但是可以肯定地檢查調用是否返回正確的結果。

現在也不可能從“較早的”執行中收集堆棧跟蹤。

我看不到模擬在這里也無法為您提供任何幫助,但是我可能會遺漏一些東西,也許我們的同事會為此提供一個示例,但是我建議采用以下方法:

  • 不需要方法是靜態的,而是要求方法是常規的。

然后使用以下技巧:

准備以下課程,但不要將其提供給希望實施“服務”課程的學生(我認為這是出於教育目的,因為您已經談論過考試,如果我錯了,抱歉)。

 class MyServiceForChecks extends Service {
      private List<StackTraceElement[]> invocationStackTraces = new ArrayList<>(); 

      public boolean containsDigit(int n, int d) { // its not static anymore
           StackTraceElement [] stackTrace =  getStackTrace();
           invocationStackTraces.add(stackTrace); 
        return super.containsDigit(n,d);
      }

      public List<StackTraceElement[]> getInvocationStackTraces () {
           return this.invocationStackTraces;
      }
 }

在JUnit中,測試MyServiceForChecks類而不是Service類。 containsDigits方法完成執行后,可以調用getInvocationStackTraces方法並分析結果。

如果無法創建MyServiceForChecks類,則可以使用CGLIB庫動態生成它。

暫無
暫無

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

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