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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With