0

In Scala, I noticed that when using when and thenReturn in Mockito, thenReturn runs the actual function before "replacing" the return value from the function. for example -

class clsToTest() {
  def functionToTest: String = {
    if(condition-that-evaluated-to-true-sometimes) {
      throw new RuntimeException("some error")
    }
    "function-completed"
  }
}

testclsToTest() {
   test("test functionToTest") {
     val spiedclsToTest = spy(new clsToTest())
     when(spiedScalaSharedLibConfigManager.functionToTest).thenReturn("value to replace")
     //spiedScalaSharedLibConfigManager.otherFunctionThatUsesFunctionToTest()
  }
}

but when the line

when(spiedScalaSharedLibConfigManager.functionToTest).thenReturn("value to replace")

is executed, because sometimes condition-that-evaluated-to-true-sometimes evaluated to True, the test fails without real reason. I'm looking for a way to replace the value of the returned function without actually running the function. I have my own reason to use spy instead of mocking.

Gaël J
  • 11,274
  • 4
  • 17
  • 32
amit
  • 71
  • 2
  • 10
  • See https://stackoverflow.com/a/67734707/5389127 – Gaël J Jul 16 '23 at 15:11
  • 1
    Does this answer your question? [Mockito - difference between doReturn() and when()](https://stackoverflow.com/questions/20353846/mockito-difference-between-doreturn-and-when) – Gastón Schabas Jul 16 '23 at 15:14
  • You're using a spy, not a mock. I wouldn't expect the `when().doReturn()` to have any impact. Consider using a mock instead – Arnaud Claudel Jul 16 '23 at 16:56

1 Answers1

1

If you have reason to use a spy, then you need to use specific syntax to mock methods of it.

when doesn't work for spies. Instead use doXxx.when(spy).method():

doReturn("value-to-replace")
  .when(spiedScalaSharedLibConfigManager)
  .functionToTest();

Another option is to use a mock rather than a spy.


References:

Gaël J
  • 11,274
  • 4
  • 17
  • 32
  • I'm running your code doReturn("value-to-replace") .when(spiedScalaSharedLibConfigManager) .functionToTest(); but when I'm running for the test scope println(spiedScalaSharedLibConfigManager.functionToTest()) I'm receiving the same error. – amit Jul 25 '23 at 07:18