是否有在java中的任何方式來檢查,如果某個方法被調用內的另一個方法是什麼?我正在測試一個課程以及播放聲音時遇到的問題,並且幾乎沒有辦法在不更改代碼的情況下播放播放的音頻文件(內部類中的專用屬性)。然而,該方法播放聲音的方式是它調用播放單個聲音的方法(playSadMusic,playHappyMusic等)。這些方法在我必須創建一個模擬對象的接口中。我有點卡在我如何精確地去測試這個。有什麼想法嗎?歡迎任何關於如何測試這個其他的想法,而不是檢查某個方法是否是電話。檢查的方法被調用內部的另一種方法
我使用JMock的2.6.0和JUnit 4
音頻inteface
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();
}
}
}
我的水晶球體說「是」哦,請提供一些代碼並說明您到目前爲止嘗試過的方法 –
您可以檢查堆棧跟蹤。 – assylias
按照John Snow。 Mockito是答案。您可以創建一個方法被調用的次數。 – Rudy