I am super new to Micronaut and I am trying a couple of things out. My end goal is to be able to deploy a Micronaut Serverless Function, built as a Native Image on AWS Lambda.
I have gone through the documentation, however, I am struggling to mock Beans in my tests. Currently, I am only trying this out with a Sample Program where I want to mock out a method call from my service. I am getting a null response for my mocked method when using Mockito in tests.
package com.example;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import io.micronaut.context.ApplicationContext;
import io.micronaut.core.annotation.Introspected;
import io.micronaut.function.aws.MicronautRequestHandler;
import jakarta.inject.Inject;
@Introspected
public class BookRequestHandler extends MicronautRequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
@Inject
private BookService bookService;
public BookRequestHandler() {
}
public BookRequestHandler(ApplicationContext applicationContext) {
super(applicationContext);
}
@Override
public APIGatewayProxyResponseEvent execute(APIGatewayProxyRequestEvent request) {
return new APIGatewayProxyResponseEvent()
.withStatusCode(200)
.withBody(bookService.sayHello());
}
}
public interface BookService {
String sayHello();
}
@Singleton
public class BookServiceImpl implements BookService {
public String sayHello() {
return "HELLO";
}
}
@MicronautLambdaTest
public class BookRequestHandlerTest {
@Inject
private BookService bookService;
@Inject
private ApplicationContext applicationContext;
@Test
public void testHandler() {
BookRequestHandler bookRequestHandler = new BookRequestHandler(applicationContext);
when(bookService.sayHello()).thenReturn("MOCKED RESPONSE");
APIGatewayProxyResponseEvent responseEvent =
bookRequestHandler.execute(new APIGatewayProxyRequestEvent());
assertEquals(responseEvent.getStatusCode(), 200);
assertEquals(responseEvent.getBody(), "MOCKED RESPONSE");
}
@MockBean(BookServiceImpl.class)
BookService bookService() {
return mock(BookService.class);
}
}
I would really appreciate it if someone could point me towards the best practice for Mocking Beans in Micronaut when developing Serverless Functions because currently, I am not able to stub my methods.
Moreover, is using @MicronautLambdaTest recommended while testing Serverless Functions? There seems to be some discrepancy between the Sample Code generated from launch and the AWS Documentation.
Any help is much appreciated :D