Amock
A JMock wrapper for Kotlin.
AmockExampleTests
shows how to write a test.
class AmockExampleTests {
@Rule @JvmField val mockery = JUnitRuleMockery()
val charSequence = mockery.mock<CharSequence>()
@Test fun `expect a call to a mock via the mockery`() {
mockery.expecting {
oneOf(charSequence).length
}
assertEquals(0, charSequence.length)
}
@Test fun `you can specify a (type-checked) return value for a call`() {
mockery.expecting {
oneOf(charSequence).length.which will returnValue(42)
}
assertEquals(42, charSequence.length)
}
@Test fun `simulate failures with throwException`() {
mockery.expecting {
oneOf(charSequence).length.which will throwException(RuntimeException("deliberate"))
}
assertFails {
charSequence.length
}
}
@Test fun `match parameters with Hamkrest`() {
mockery.expecting {
oneOf(charSequence).get(0).which will returnValue('*')
oneOf(charSequence).get(with(greaterThan(0))).which will returnValue('-')
}
assertEquals('-', charSequence.get(1))
assertEquals('*', charSequence.get(0))
}
@Test fun `which-will can take a lambda`() {
var count = 0
mockery.expecting {
allowing(charSequence)[with(isA<Int>())].which will {
count++
' '
}
}
assertEquals(' ', charSequence[0])
assertEquals(' ', charSequence[1])
assertEquals(2, count)
}
@Test fun `invoke action can take a lambda to do complicated things`() {
mockery.expecting {
allowing(charSequence)[with(isA<Int>())].which will invoke("return alternating values") { invocation ->
val index = invocation.getParameter(0) as Int
if (index % 2 == 0) '+' else '-'
}
}
assertEquals('+', charSequence[42])
assertEquals('-', charSequence[43])
assertEquals('-', charSequence[-1])
}
val controlPanel = Panel(
mockery.mock<Key>("key1"),
mockery.mock<Key>("key2"),
mockery.mock<Missile>())
@Test fun `specify expectations before and after action`() {
mockery.given {
allowing(controlPanel.key1).isTurned.which will returnValue(true)
allowing(controlPanel.key2).isTurned.which will returnValue(true)
}.whenRunning {
controlPanel.pressButton()
}.thenExpect {
oneOf(controlPanel.missile).launch()
}
}
@Test fun `better check we're safe`() {
mockery.given {
allowing(controlPanel.key1).isTurned.which will returnValue(true)
allowing(controlPanel.key2).isTurned.which will returnValue(false)
}.whenRunning {
controlPanel.pressButton()
}.thenExpect {
never(controlPanel.missile).launch()
}
}
}
Amock is available at Maven central.