Skip to content

Instantly share code, notes, and snippets.

@jvmvik
Created October 1, 2013 17:30
Show Gist options
  • Save jvmvik/6782130 to your computer and use it in GitHub Desktop.
Save jvmvik/6782130 to your computer and use it in GitHub Desktop.
Groovy mocking static method. This is a fairly good example of how to correctly mock any groovy object without destroying your all regression.
/*
* Groovy Test Mocking explains.
*
* A modification of metaClass static method apply to the class inside the JVM.
* You run your test with fork mode enabled, each test is isolated from another at the leve of a class or method.
* However you can delete the metaClass behavior by
* MyClass.metaClass = null
*
* Must know
* - The metaClass method signature is very important. The documentation does not higlight that the method signature must match exactely:
* e.g.: Arrays.sort(String[] arrays) <==> Arrays.metaClass.'static'.sort = { String[] a -> // do something }
*
* Requierement :
* - Groovy 2.1.6
* - JUnit 4.1x
*/
import org.junit.After
import org.junit.Before
import org.junit.Test
class ArraysTest
{
@Before
void setUp()
{}
@After
void tearDown()
{
// You should reset metaClass between test
//Arrays.metaClass = null
}
@Test
void basic()
{
String[] things = [ 'dog', 'ant', 'bee', 'cat' ]
// non-mocked first to prove it works normally
Arrays.sort(things)
assert ["ant", "bee", "cat", "dog"] == things
// Replace sort default behaviors
Arrays.metaClass.'static'.sort = { String[] a ->
a[0] = 'ewe'
a[1] = 'fox'
}
// Sort again
things = [ 'dog', 'ant', 'bee', 'cat' ]
Arrays.sort(things)
// item 0 & 1 have changed
assert ["ewe", "fox", "bee", "cat"] == things
}
@Test
void sideEffect()
{
// This test is affect by the sort behavior
// Sort again
String[] things = [ 'dog', 'ant', 'bee', 'cat' ]
Arrays.sort(things)
// item 0 & 1 have changed
assert ["ewe", "fox", "bee", "cat"] == things
Arrays.metaClass = null
things = [ 'dog', 'ant', 'bee', 'cat' ]
Arrays.sort(things)
// item 0 & 1 have changed
assert ["ant", "bee", "cat", "dog"] == things
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment