Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Java static class from scala

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.

like image 720
paul Avatar asked Apr 11 '26 00:04

paul


1 Answers

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.

like image 125
Vadym Chekan Avatar answered Apr 12 '26 12:04

Vadym Chekan