Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a method was called inside another method

Tags:

java

junit

jmock

Is there any way in java to check if a certain method was called inside another method? I am testing a class and the method I am having trouble with plays sound and there is virtually no way of getting the audio file that is played(private attribute inside an inner class) without changing the code. However the way the method plays sounds is it calls a method that plays a single sound (playSadMusic, playHappyMusic, etc). Those methods are in an interface that I have to create a mock object for. I'm a little stuck on how I would exactly go about testing this. Any thoughts? Any other ideas on how I could possibly test this other than check if a certain method was call are welcome.

I am using JMock 2.6.0 and JUnit 4

the audio inteface

public interface StockTickerAudioInterface {

    public abstract void playHappyMusic();

    public abstract void playSadMusic();

    public abstract void playErrorMusic();
}

anther interface I have to create a mock for

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);

}

the class being tested

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();
        }
    }

}
like image 294
user2337029 Avatar asked May 15 '13 07:05

user2337029


People also ask

Can a method be called from another method?

We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .

How do you call a method from another method in the same class?

Example: public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called. Method2(); // Method being called. } // Method definition to call in another Method public static void Method1() { System. out.

Can you call a method within the same method?

But yes, what you're trying to do is possible. It's called recursion, or recursive programming. It's when a function calls itself or multiple functions call each other repeatedly.


1 Answers

If you use Mockito you can use verify() to check the number of times a method was called. Use it like this:

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

You can check if methodToValidate() was called with a specific string, e.i verify(mockedObject, times(1)).methodToValidate("a specific value"); or you can use it with anyString() like this: verify(mockedObject, times(1)).methodToValidate(anyString());.

Unless this method is called with your specified paramterer, the test will fail

Read more about verify here.

UPDATE

Since your edited post states that you are using jMock, a quick googeling showed me that it is possible to achieve a similar behaviour with jMock and it's expect method. It's used as below:

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

More detailed explanation can be found by reading jMocks getting started page.

like image 161
John Snow Avatar answered Sep 24 '22 13:09

John Snow