Mock Java static class from scala
Asked Answered
M

1

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.

Mezzotint answered 3/11, 2017 at 13:24 Comment(2)
Have you looked at How do I mock static function (Object function, not class function) in scala?Heavy
I’m afraid not yet. Seems like it’s not a very extended topic. At least not in mockito power mockMezzotint
A
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.

Augmenter answered 7/2, 2023 at 0:23 Comment(2)
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 blockAmmoniacal
@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.Augmenter

© 2022 - 2024 — McMap. All rights reserved.