Skip to content

Instantly share code, notes, and snippets.

@FrancescoJo
Last active June 27, 2018 09:32
Show Gist options
  • Save FrancescoJo/51961baaed8f9c5343eabdea98728e95 to your computer and use it in GitHub Desktop.
Save FrancescoJo/51961baaed8f9c5343eabdea98728e95 to your computer and use it in GitHub Desktop.
Unit testing with JUnit+Mockito vs. Spock. Have a look how Spock usage is concise than traditional JUnit side.
class EvenOddPickGame(private val randomIntGen : RandomValueGenerator<Integer>) {
fun pick(times: Int): List<String> {
return ArrayList<String>().apply {
for (i in 0 until times) {
val rolled = randomIntGen.nextRandom(lowerBound = 1, upperBound = 2) % 2
if (rolled == 0) {
add("EVEN")
} else {
add("ODD")
}
}
}
}
}
interface RandomValueGenerator<T> {
fun nextRandom(lowerBound: T? = null, upperBound: T? = null): T
}
class RandomIntGenerator : RandomValueGenerator<Int> {
override fun nextRandom(lowerBound: Int?, upperBound: Int?): Int {
return with(Random()) {
(lowerBound ?: 0) + if (upperBound == null) {
nextInt()
} else {
nextInt(upperBound)
}
}
}
}
// JUnit + Mockito
@Test
public void testPick() {
// setup (given)
final RandomValueGenerator<Integer> mockRandomIntGen = mock(RandomValueGenerator.class);
final EvenOddPickGame sut = new EvenOddPickGame(mockRandomIntGen);
doAnswer(new Answer<Integer>() {
private int count = 0;
public Integer answer(final InvocationOnMock invocation) {
count++;
switch (count) {
case 1:
return 4;
case 2:
return 9;
default:
throw new UnsupportedOperationException("Out of specification")
}
}
}).when(mockRandomIntGen).nextRandom(anyInt(), anyInt());
// replay (then)
final List<String> expected = new ArrayList<>(Arrays.listOf("EVEN", "ODD"))
final List<String> actual = sut.pick(2);
// verify (expect)
assertListEquals(actual, expected)
}
// Spock
def "Verify roll mod 2 yields correct #result"() {
given:
final mockRandomIntGen = Mock(RandomValueGenerator);
final sut = new EvenOddPickGame(mockRandomIntGen);
mockRandomIntGen.nextRandom(_, _) >>> [ roll1, roll2 ]
expect:
sut.pick(2) == result
where:
roll1 || roll2 || result
4 || 9 || [ "EVEN", "ODD" ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment