mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.09k stars 198 forks source link

How to use "any" with a lambda? #520

Open austinarbor opened 2 weeks ago

austinarbor commented 2 weeks ago

I am trying to mock the AWS Kotlin SDK, but getting an error I cannot figure out. I am trying to stub out the SDK function public suspend inline fun StsClient.getFederationToken(crossinline block: GetFederationTokenRequest.Builder.() -> Unit): GetFederationTokenResponse = getFederationToken(GetFederationTokenRequest.Builder().apply(block).build())

When using any<GetFederationTokenRequest.Builder.() -> Unit>(), I get the error

java.lang.NullPointerException: Cannot invoke "kotlin.jvm.functions.Function1.invoke(Object)" because "block$iv" is null

Can you let me know what I'm doing wrong, or if there is a better way of achieving this?

Thank you!

build.gradle.kts:

plugins {
    kotlin("jvm") version "2.0.0"
    application
}

dependencies {
    implementation("aws.sdk.kotlin:sts:1.2.38")
    testImplementation("org.mockito:mockito-junit-jupiter:5.12.0")
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
    testImplementation("org.mockito.kotlin:mockito-kotlin:5.3.1")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.1")
}

test

@Test
  fun testSts() = runTest {
    val client = mock<StsClient> {
      onBlocking { getFederationToken(any<GetFederationTokenRequest.Builder.() -> Unit>()) } doReturn GetFederationTokenResponse {
        credentials = Credentials {
          accessKeyId = "accessKey"
          secretAccessKey = "secretKey"
          sessionToken = "sessionToken"
          expiration = Instant.now().toSdkInstant()
        }
      }
    }

    client.getFederationToken {
      name = "test-name"
      policy = "{}"
    }

    argumentCaptor<GetFederationTokenRequest.Builder.() -> Unit>().apply {
      verify(client.getFederationToken(capture()))
      val builtRequest = GetFederationTokenRequest {
        firstValue.invoke(this)
      }
      assertEquals(builtRequest.name, "test-nam")
    }
  }