Gmock is a mocking framework for the Groovy language.
This documention describes the version 0.3 of Gmock.
import org.gmock.GMockTestCase
class LoaderTest extends GMockTestCase {
void testLoader(){
def mockLoader = mock()
mockLoader.load('key').returns('value')
play {
assertEquals "value", mockLoader.load('key')
}
}
}
The code under test should run through the play closure.
void testBasic(){
def aMock = mock()
// set up expectation
play {
// run your code
}
}
def loader = mock()
loader.put("fruit").returns("apple")
play {
assertEquals "apple", loader.put("fruit")
}
Exceptions can be set up using the raises keyword.
def loader = mock()
loader.put("throw exception").raises(new RuntimeException("an exception"))
play {
try {
loader.put("throw exception")
} catch (RuntimeException e){
assertEquals "an exception", e.message
}
}
If you don't care how many times a method is called or not called at all you can stubbed it.
def loader = mock()
loader.put("fruit").returns("apple").stub()
play {
assertEquals "apple", loader.put("fruit")
assertEquals "apple", loader.put("fruit")
}
Property calls should be mocked using the following syntax. For Setters and getters
def loader = mock()
loader.name.sets("a name")
loader.name.returns("a different name")
play {
loader.name = "a name"
assertEquals "a different name", loader.name
}
Support for exceptions and method stubs are similar to standard method calls. Ex:
Mocking static method calls is similar to standard method calls, just add the static keyword:
def mockMath = mock(Math)
mockMath.static.random().returns(0.5)
play {
assertEquals 0.5, Math.random()
}
Constructor calls are mocked using the following syntax:
def mockFile = mock(File, constructor("/a/path/file.txt"))
def mockFile = mock(File, constructor: ["/a/path/file.txt"])
mockFile.getName().returns("file.txt")
play {
def file = new File("/a/path/file.txt")
assertEquals "file.txt", file.getName()
}
void testController(){
def gmc = new GMockController()
def mockLoader = gmc.mock()
mockLoader.load('key').returns('value')
gmc.play {
assertEquals "value", mockLoader.load('key')
}
}