0

I have an object that contain a private method(mylog), when I want to mock a method(myMethod) that call the private method it throw me an exception

Caused by: java.lang.NullPointerException

Here my code :

object myObject {

  private val mylog = new Logger("Title")

  def myMethod(parameter1: Int): Int = {
    mylog.info("I log a message here")
    parameter1
  }
}

Here my mock method

withObjectMocked[myObject.type] {
          when(myObject.myMethod(ArgumentMatchers.any()).thenCallRealMethod()
    [...]
}
FTK
  • 43
  • 4
  • Well, of course ... `mylog` is null. Make it public and mock it. Or use `spy` instead of `mock` (not usually recommended). You could also use `PowerMock` as described in the second answer [here](https://stackoverflow.com/questions/36173947/mockito-mock-private-field-initialization), but personally I think, that is even uglier than `spy`. But at a higher level, calling real methods in mocked objects is "code smell". It suggests that your code can benefit from some refactoring to make it more unit-test-friendly. – Dima Mar 02 '21 at 14:17
  • thank your answer. I'll try it – FTK Mar 04 '21 at 10:14
  • are you using Mockito-core or Mockito-scala? I am guessing Mockito-scala because you use withObjectMocked – l33tHax0r Mar 09 '21 at 22:24

0 Answers0