mockito-scala icon indicating copy to clipboard operation
mockito-scala copied to clipboard

withObjectSpied call real method instead of stubbed

Open flo076 opened this issue 3 years ago • 2 comments

Hello

In 1.17.12 of mockito-scala we have a strange behavior. The method "simpleMethod" is really call. If we launch the tests "with Spied", the temporary file is created and the method throw "java.lang.ArithmeticException: / by zero". On the contrary the test "with Mock" doesn't have problem. I don't understand why ? It looks as a bug.

object FooObject {

  def simpleMethod: Int = {
    println("simple method")
    val tmp = Files.createTempFile("simpleMethod", "txt")
    println(s"tmp file path : ${tmp.toFile.getPath}")
    100 / 0
  }

}

class Test extends AnyWordSpec with Matchers with ArgumentMatchersSugar with IdiomaticStubbing {
  "mock" should {
    "with Mock" in {
      withObjectMocked[FooObject.type] {
        FooObject.simpleMethod returns 42
        FooObject.simpleMethod shouldBe 42
      }
    }
    "with Spied" in {
      withObjectSpied[FooObject.type] {
        FooObject.simpleMethod returns 52
        FooObject.simpleMethod shouldBe 52
      }
    }
  }
}

flo076 avatar Sep 30 '22 13:09 flo076

I also encountered a similar issue with this code:

class RunnerTest extends AnyFlatSpec with IdiomaticMockito {
  "runner" should "expire snapshots" in {
    val mockRedis = mock[Redis]
    val svc = new Service(mockRedis, null, null)
    val mockService: Service = spy(svc ,lenient = true)
    when(mockService.someMethod("db", "table")).thenReturn(()) // this line fails with java.lang.NullPointerException was thrown and the stack shows that the actual method was called
  }
}

sushi30 avatar Nov 08 '23 15:11 sushi30