Skip to content

Instantly share code, notes, and snippets.

@satr
Created May 15, 2019 18:52
Show Gist options
  • Save satr/73af79cc4d2adaf8bd59c5e415d76c22 to your computer and use it in GitHub Desktop.
Save satr/73af79cc4d2adaf8bd59c5e415d76c22 to your computer and use it in GitHub Desktop.
Mock Lambda Context and Logger while testing AWS Lambda RequestHandler (with JUnit4)
//In the test class
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.Mock;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.ArgumentMatchers.anyString;
@RunWith(MockitoJUnitRunner.class)//without this runner - mocks would be "null"
public class LambdaRequestHandlerTest {
private LambdaRequestHandler handler;
@Mock
Context context;
@Mock
LambdaLogger loggerMock;
@Before
public void setUp() throws Exception {
when(context.getLogger()).thenReturn(loggerMock);
doAnswer(call -> {
System.out.println((String)call.getArgument(0));//print to the console
return null;
}).when(loggerMock).log(anyString());
handler = new LambdaRequestHandler();
}
@Test
public void handleRequest() {
String respond = handler.handleRequest("some input", context);
}
}
//In the request handler
public class LambdaRequestHandler implements RequestHandler<String, String> {
@Override
public String handleRequest(String input, Context context) {
LambdaLogger logger = context.getLogger();
logger.log("some log message");
return "some output";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment