Skip to content

Instantly share code, notes, and snippets.

@tzachz
Created September 17, 2019 18:27
Show Gist options
  • Save tzachz/f448644f31efc14c5795cb1f71e8b53f to your computer and use it in GitHub Desktop.
Save tzachz/f448644f31efc14c5795cb1f71e8b53f to your computer and use it in GitHub Desktop.
Mockito gotcha: full test
class MyServiceSpec extends FlatSpec with Matchers with MockitoSugar with BeforeAndAfter {
private val dependency: MyOtherService = mock[MyOtherService]
private val underTest = new MyService(dependency)
before { // default for most tests:
when(dependency.getValue(any())).thenAnswer(answerSizeOfInputPlus(2))
}
"MyService.testedMethod" should "return output from getValue plus one" in {
// override default for this test:
when(dependency.getValue(any())).thenAnswer(answerSizeOfInputPlus(3))
underTest.testedMethod("Hello") shouldBe 5 + 3 + 1
}
private def answerSizeOfInputPlus(add: Int): Answer[Int] = invocation => {
val inputArg: String = invocation.getArgumentAt(0, classOf[String])
inputArg.length + add
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment