Skip to content

Instantly share code, notes, and snippets.

@ran488
Created June 1, 2011 18:51
Show Gist options
  • Save ran488/1003004 to your computer and use it in GitHub Desktop.
Save ran488/1003004 to your computer and use it in GitHub Desktop.
Simple sample of using Groovy's dynamic stubs for testing
package com.XXXXX.XXX
import static org.junit.Assert.*
import groovy.mock.interceptor.*
import java.util.List
import org.junit.*
class StubTest {
@Test
public void testThatIGetAListOfMonkeys() {
//create the stub...
def stub = new StubFor(Monkey.class)
// and override the behavior of the findMonkeys method....
stub.demand.with {
findMonkeys {
[
"Rhesus",
"Spider",
"Marmoset"
]
}
}
// creating MyMonkey in this closure will create the stub version...
stub.use {
def f = new Monkey()
def monkeys = f.findMonkeys()
monkeys.each { println(it) }
assertEquals(3,monkeys.size)
}
// outside, the "real" version, calling the "real" findMonkeys method....
Monkey m = new Monkey()
def realMonkeys = m.findMonkeys()
realMonkeys.each { println(it) }
assertEquals(2,realMonkeys.size)
}
}
class Monkey {
/* Let's pretend this method does something like
* DB access, web services calls, directory lookups,
* or other external resource not under test.... */
List findMonkeys() {
[
"Curious George",
"Flying Monkeys"
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment