簡體   English   中英

檢查是否在另一個方法中調用了一個方法

[英]Check if a method was called inside another method

在java中有沒有辦法檢查某個方法是否在另一個方法中被調用? 我正在測試一個類和我遇到播放聲音問題的方法,實際上沒有辦法獲取播放的音頻文件(內部類中的私有屬性)而不更改代碼。 然而,該方法播放聲音的方式是調用播放單個聲音的方法(playSadMusic,playHappyMusic等)。 這些方法在我必須為其創建模擬對象的接口中。 我有點堅持我將如何測試這個。 有什么想法嗎? 關於我如何測試這個以外的任何其他想法,而不是檢查某個方法是否被調用是受歡迎的。

我正在使用JMock 2.6.0和JUnit 4

音頻接口

public interface StockTickerAudioInterface {

    public abstract void playHappyMusic();

    public abstract void playSadMusic();

    public abstract void playErrorMusic();
}

花葯界面我必須創建一個模擬

public interface StockQuoteGeneratorInterface {
    public abstract StockQuoteInterface getCurrentQuote() throws Exception;

    public abstract String getSymbol();

    public abstract void setSymbol(String symbol);

    public abstract StockQuoteGeneratorInterface createNewInstance(String symbol);

}

正在測試的課程

public class StockQuoteAnalyzer {
    private StockTickerAudioInterface audioPlayer = null;
    private String symbol;
    private StockQuoteGeneratorInterface stockQuoteSource = null;

    private StockQuoteInterface lastQuote = null;
    private StockQuoteInterface currentQuote = null;


    public StockQuoteAnalyzer(String symbol,
        StockQuoteGeneratorInterface stockQuoteSource,
        StockTickerAudioInterface audioPlayer)
        throws InvalidStockSymbolException, NullPointerException,
        StockTickerConnectionError {
        super(); 

    // Check the validity of the symbol.
        if (StockTickerListing.getSingleton().isValidTickerSymbol(symbol) == true){
            this.symbol = symbol;
        } else {
        throw new InvalidStockSymbolException("Symbol " + symbol
                + "not found.");
        }
        if (stockQuoteSource == null) {
             throw new NullPointerException(
                "The source for stock quotes can not be null");
        }
        this.stockQuoteSource = stockQuoteSource;
        this.audioPlayer = audioPlayer;
    }
    public double getChangeSinceLast() {
        double retVal = 0.0;
        if (this.lastQuote != null) {
            double delta = this.currentQuote.getLastTrade() - this.lastQuote.getLastTrade();
            retVal = 100 * (delta / this.lastQuote.getLastTrade());
           }
           return retVal;
    }

    public double getChangeSinceYesterday() {
        double delta = (this.currentQuote.getLastTrade() - this.currentQuote
            .getClose());
        return 100 * (delta / this.currentQuote.getClose());

    }

    public void playAppropriateAudio() {
        if ((this.getChangeSinceYesterday() > 2)
            || (this.getChangeSinceLast() > 0.5)) {
            audioPlayer.playHappyMusic();
    }

        if ((this.getChangeSinceYesterday() < -2)
            || (this.getChangeSinceLast() < -0.5)) {
            audioPlayer.playSadMusic();
        }
    }

}

如果您使用Mockito您可以使用verify()來檢查方法被調用的次數。 像這樣使用它:

verify(mockedObject, times(1)).methodToValidate();

您可以檢查是否使用特定字符串調用methodToValidate() ,ei verify(mockedObject, times(1)).methodToValidate("a specific value") ; 或者你可以像anyString()一樣使用它: verify(mockedObject, times(1)).methodToValidate(anyString());

除非使用指定的參數調用此方法,否則測試將失敗

閱讀更多關於驗證的信息

UPDATE

由於您編輯的帖子表明您正在使用jMock,因此快速googeling向我展示了使用jMock實現類似的行為並且它是expect方法。 它的用法如下:

mockedObject.expects(once()).method("nameOfMethod").with( eq("An optional paramter") );

通過閱讀jMocks 入門頁面可以找到更詳細的說明。

假設你有一個方法child()parent()調用

public void parent() {
  child();
}

child()中獲取它調用的最后一個方法,你可以使用StackTraceElement

public void child() {
  StackTraceElement[] traces = Thread.currentThread().getStackTrace();
  boolean check = false;
      for(StackTraceElement element : traces) {
         if(check) {
            System.out.println("Calling method - " + element.getMethodName());
         }
         if(element.getMethodName().equals("child")) {
        check = true;
         }
      }
}

如果您正在使用要檢查它們是否被調用的方法編寫模擬對象,則可以通過在調用它們時引發某些標志的方式來實現這些方法,例如

public void playHappyMusic() {
    this.wasCalled = true;
}

wasCalled是一個公共(或帶有getter)類變量。 然后你只需檢查標志。

假設您與調用方法位於同一個線程中,您可以通過以下方式檢查堆棧跟蹤:

Thread.currentThread().getStackTrace()

你可以看到這樣做的方法是這樣做的:

for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
            System.out.println(ste);
        }

例如:

public class Test {

    public static void main (String[]s){
        Test  test = new Test();
        test.makeTest();
    }

    public void makeTest(){
        for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
            System.out.println(ste);
        }
    }

結果是

java.lang.Thread.getStackTrace(Unknown Source)
Test.makeTest(Test.java:17)
Test.main(Test.java:11)

暫無
暫無

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

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