2

我想用我的应用程序模拟此处MicronautLambdaHandler记录的协作者,但如果您只是MicronautLambdaHandler通过调用其构造函数进行实例化,它显然不会从您的测试上下文中获取任何内容。

具体来说,这不能按预期工作:

import com.amazonaws.serverless.proxy.internal.testutils.AwsProxyRequestBuilder
import com.amazonaws.serverless.proxy.internal.testutils.MockLambdaContext
import com.amazonaws.services.lambda.runtime.Context
import com.fasterxml.jackson.databind.ObjectMapper
import io.micronaut.context.ApplicationContext
import io.micronaut.context.ApplicationContextBuilder
import io.micronaut.context.annotation.Factory
import io.micronaut.context.env.Environment
import io.micronaut.http.HttpHeaders
import io.micronaut.http.HttpMethod
import io.micronaut.http.HttpStatus
import io.micronaut.http.MediaType
import org.junit.jupiter.api.Test
import io.micronaut.function.aws.proxy.MicronautLambdaHandler
import io.micronaut.security.authentication.AuthenticationException
import io.micronaut.security.authentication.AuthenticationFailed
import io.micronaut.security.authentication.AuthenticationProvider
import io.micronaut.security.authentication.AuthenticationResponse
import io.micronaut.test.annotation.MockBean
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import io.mockk.every
import io.mockk.mockk
import io.reactivex.Maybe
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.reactivestreams.Publisher
import java.lang.RuntimeException
import javax.inject.Inject

@MicronautTest
class ManualInstantiationTest {
    @Inject
    lateinit var objectMapper: ObjectMapper

    @Inject
    lateinit var authenticationProvider: AuthenticationProvider

    @MockBean(AuthenticationProvider::class)
    fun authenticationProviderMock() = mockk<AuthenticationProvider>()

    @Test
    fun testLoginHandler() {
        every { authenticationProvider.authenticate(any(), any()) } answers {
            Maybe.error<AuthenticationResponse>(
                AuthenticationException(
                    AuthenticationFailed("Incorrect password")
                )
            ).toFlowable()
        }

        val handler = MicronautLambdaHandler()
        val loginRequest = Registration("username", "password")
        val json = objectMapper.writeValueAsString(loginRequest)
        val request = AwsProxyRequestBuilder("/login", HttpMethod.POST.toString())
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .body(json)
            .build()
        val lambdaContext: Context = MockLambdaContext()
        // this.authenticationProvider is never used
        val response = handler.handleRequest(request, lambdaContext)
    }
}

我也尝试过@Injecttype 的字段MicronautLambdaHandler,但失败了,因为没有注册该类型的 bean。

4

1 回答 1

0

Micronaut 暂时不支持测试 lambdas @MicronautTestMicronautLambdaHandlerMicronautRequestHandler创建自己的上下文,与@MicronautTest实际注册模拟的配置完全分开。它们也不是豆子,所以注入它们什么也没做。

这是一个已知问题(例如,请参见此处)并且正在处理中。

于 2020-11-25T23:34:53.570 回答