Saturday, June 23, 2012

MockFor

//http://groovy.codehaus.org/Using+MockFor+and+StubFor

import groovy.mock.interceptor.*

/*sample data class*/
class Movie {
    // Lots of expensive method calls, etc.
}

/*helper class*/
class MovieAnalyzer {
    def isGood( movie ) {
        if( movie.hasGalifinakis() )
            return true;
        else if( movie.hasSparklyVampires() )
            return false;

        return ( new Date().getTime() / 2 ) == 0 
    }
}

/*unit test the helper class by mocking the data class*/
def testTwitlightMovie(){
    def mock = new MockFor(Movie)
    //StubFor is similar to MockFor except that 
    //the expectaion of methods called is order independent ...
    mock.demand.hasGalifinakis { true }
    mock.demand.hasSparklyVampires( 0..1 ) { true } // demand the method 0 or 1 times
    mock.use {
       assert true == new MovieAnalyzer().isGood( new Movie() )
    }
}

testTwitlightMovie()

No comments:

Post a Comment