11

Any idea how from ScalaTest I can mock a static Java class??

I have this code

  val mockMapperComponent: IMapperComponent = mock[IMapperComponent]
  val applicationContext: ApplicationContext = mock[ApplicationContext]

  val appContextUtil: AppContextUtil = mock[AppContextUtil]


  override def beforeAll(): Unit = {
    mockStatic(classOf[AppContextUtil])
    when(AppContextUtil.getApplicationContext).thenReturn(applicationContext)
    when(applicationContext.getBean(classOf[IMapperComponent])).thenReturn(mockMapperComponent)

  }

In Java mockStatic with the annotation in the class @PrepareForTest({AppContextUtil.class}) do the trick, but from Scala I can only found in scalaTest documentation how to mock the normal access, but not static.

Regards.

paul
  • 12,873
  • 23
  • 91
  • 153
  • Have you looked at [How do I mock static function (Object function, not class function) in scala](https://stackoverflow.com/questions/5696815/how-do-i-mock-static-function-object-function-not-class-function-in-scala)? – Alexandre Dupriez Nov 12 '17 at 23:19
  • I’m afraid not yet. Seems like it’s not a very extended topic. At least not in mockito power mock – paul Nov 12 '17 at 23:20

1 Answers1

3

Mocking Java static method in Scala is more involved than in Java because Mockito API use Java's ability to implicit cast a single-function interface to pointer of a function, for example: httpClientStaticMock.when(HttpClientBuilder::build).thenReturn(httpClientBuilder); notice function pointer usage: HttpClientBuilder::build.

As scala compiler does not have the same implicit casting rules, we have to de-sugar this call explicitly:

val httpClientStaticMock = mockStatic(classOf[org.apache.http.impl.client.HttpClientBuilder])
try {
  httpClientStaticMock.when(new org.mockito.MockedStatic.Verification {
    override def apply(): Unit = org.apache.http.impl.client.HttpClientBuilder.create()
  }).thenReturn(httpClientBuilder)

} finally {
  httpClientStaticMock.close()
}

Notice anonymous object usage to implement Verification interface: new org.mockito.MockedStatic.Verification.

Also, pay attention and do NOT forget to close static mocks in finally clause, otherwise very hard to troubleshoot errors will happen.

Vadym Chekan
  • 4,977
  • 2
  • 31
  • 24
  • Can you explain what the block: ```new org.mockito.MockedStatic.Verification``` does? I'm trying to mock ```LocalDateTime.now``` and I don't get what I'm sopose to do inside the block – Miguel Salas Aug 08 '23 at 16:47
  • 1
    @MiguelSalas It calls a static function to be verified. In your case, it would be `LocalDateTime.now` and then in `thenReturn` you should provide mocking value. – Vadym Chekan Aug 08 '23 at 18:21