Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

withObjectSpied call real method instead of stubbed #468

Open
flo076 opened this issue Sep 30, 2022 · 2 comments
Open

withObjectSpied call real method instead of stubbed #468

flo076 opened this issue Sep 30, 2022 · 2 comments

Comments

@flo076
Copy link

flo076 commented Sep 30, 2022

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
      }
    }
  }
}
@sushi30
Copy link

sushi30 commented Nov 8, 2023

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
  }
}

@lvieirasilva
Copy link

lvieirasilva commented Nov 28, 2024

Yeah, I have the same error here. Have you found a workaround for it?

edit: This is not an error, this is the expected behaviour for spies on Mockito. This stack overflow answer has a good explanation about it: https://stackoverflow.com/a/11620196

In this case we should use mockito's doReturn syntax, that mockito-scala translate this way:
doReturn("mocked!").when(aMock).bar <=> "mocked!" willBe returned by aMock.bar

Using @sushi30 example, () willBe returned by mockService.someMethod("db", "table") will work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants