Created
March 1, 2017 06:06
-
-
Save dirkjot/623f2e899d8d23c7975e689407bcc713 to your computer and use it in GitHub Desktop.
Using junit4 with Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// based on groovy docs | |
class Person { | |
String first, last | |
} | |
class Family { | |
Person father, mother | |
def nameOfMother() { "$mother.first $mother.last" } | |
def nameOfFather() { "$father.first $father.last" } | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovy.mock.interceptor.MockFor | |
import org.junit.Test | |
import static org.junit.Assert.assertThat | |
import static org.hamcrest.CoreMatchers.notNullValue | |
import static org.hamcrest.CoreMatchers.nullValue | |
import static org.hamcrest.CoreMatchers.is | |
import static org.hamcrest.CoreMatchers.not | |
import static org.hamcrest.CoreMatchers.equalTo | |
import static org.hamcrest.CoreMatchers.instanceOf | |
import static org.hamcrest.CoreMatchers.sameInstance | |
import static org.hamcrest.CoreMatchers.any | |
import static org.hamcrest.CoreMatchers.anything | |
import static org.hamcrest.CoreMatchers.allOf | |
import static org.hamcrest.CoreMatchers.anyOf | |
class PersonTest { | |
@Test | |
void mary() { | |
def mary = new Person(first: 'Mary', last: 'Smith') | |
// with groovy 'power' assert: | |
assert mary.first == 'Mary' | |
} | |
@Test void maryFirstSameInstanceAs() { | |
def name = 'Mary' | |
def mary = new Person(first: name, last: 'Smith') | |
// using assertThat + Hamcrest matchers | |
assertThat "are instance equal", mary.first, is(sameInstance(name)) | |
} | |
@Test void maryWithMock() { | |
// using groovy mockFor http://groovy-lang.org/testing.html | |
def mock = new MockFor(Person) | |
mock.demand.getFirst{ -> 'dummy' } | |
mock.demand.getLast{ -> 'name' } | |
mock.demand.getFirst{ 'second' } | |
mock.demand.getLast{ 'N2M2' } | |
mock.use { | |
def mary = new Person(first:'Mary', last:'Smith') | |
def f = new Family(mother:mary) | |
f.father = new Person(first:'Frank', last:'Oz') | |
assert f.nameOfMother() == 'dummy name' | |
assert f.nameOfFather() == 'second N2M2' | |
} | |
mock.expect.verify() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment