Skip to content

Instantly share code, notes, and snippets.

@handstandsam
Last active Jun 8, 2020
Embed
What would you like to do?
Wrapping Mockito Mocks for Reusability
/** Whether the Oven command was successful, or something happened */
sealed class OvenResult {
object Success : OvenResult()
data class Failure(val e: Exception) : OvenResult()
}
/** Class we will use Mockito to Mock */
class Oven {
fun setTemperatureFahrenheit(tempF: Int) {
TODO("Implementation Goes Here")
}
fun setTimeMinutes(minutes: Int) {
TODO("Implementation Goes Here")
}
fun start(): OvenResult {
TODO("Implementation Goes Here")
}
}
/** Class that uses [Oven] */
class Dessert(val oven: Oven) {
fun bakeCake(): OvenResult {
oven.setTemperatureFahrenheit(350)
oven.setTimeMinutes(30)
return oven.start()
}
}
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Test
/** Test Dessert Baking */
class DessertTest {
@Test
fun bakeCakeSuccess() {
val oven: Oven = mock()
val dessert = Dessert(oven)
// Mock Setup
whenever(oven.start()).thenReturn(OvenResult.Success)
// Execute Code
dessert.bakeCake()
// Verification
verify(oven).setTemperatureFahrenheit(350)
verify(oven).setTimeMinutes(30)
}
}
/** Wraps the Mockito mock for reuse */
class FakeOven {
val mock: Oven = mock()
fun givenOvenResult(ovenResult: OvenResult) {
// Mock Setup
whenever(mock.start()).thenReturn(ovenResult)
}
fun thenOvenSetTo(temperatureFahrenheit: Int, timeMinutes: Int) {
// Verification
verify(mock).setTemperatureFahrenheit(temperatureFahrenheit)
verify(mock).setTimeMinutes(timeMinutes)
}
}
class DessertTestWithFake {
@Test
fun bakeCakeSuccess() {
val fakeOven = FakeOven()
val dessert = Dessert(fakeOven.mock)
fakeOven.givenOvenResult(OvenResult.Success)
dessert.bakeCake()
fakeOven.thenOvenSetTo(
temperatureFahrenheit = 350,
timeMinutes = 30
)
}
}
class DessertTestsWithFake {
@Test
fun bakeCake() {
val fakeOven = FakeOven()
val dessert = Dessert(fakeOven.mock)
fakeOven.givenOvenResult(OvenResult.Success)
dessert.bakeCake()
fakeOven.thenOvenSetTo(
temperatureFahrenheit = 350,
timeMinutes = 30
)
}
@Test
fun bakeCupcakes() {
val fakeOven = FakeOven()
val dessert = Dessert(fakeOven.mock)
fakeOven.givenOvenResult(OvenResult.Success)
dessert.bakeCupcakes()
fakeOven.thenOvenSetTo(
temperatureFahrenheit = 350,
timeMinutes = 20
)
}
@Test
fun bakeCookie() {
val fakeOven = FakeOven()
val dessert = Dessert(fakeOven.mock)
fakeOven.givenOvenResult(OvenResult.Success)
dessert.bakeCupcakes()
fakeOven.thenOvenSetTo(
temperatureFahrenheit = 375,
timeMinutes = 16
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment