ChrisRTech
ChrisRTech

Reputation: 577

Invoke Java Lambda from SDK that accepts SQSEvent

I have a Lambda written in Java with this handler signature:

public class MessageListenerHandler implements RequestHandler<SQSEvent, Map<String, Object>> {
 public Map<String, Object> handleRequest(SQSEvent event, Context context) {
   // Implementation here
 }
}

Normally this Lambda is triggered by an SQS message sent to a queue. I want to be able to invoke this Lambda from a standalone java client e.g. JUnit for test purposes. Is it just a matter of creating an SQS event manually and somehow invoking the Lambda? Thanks in advance

Upvotes: 4

Views: 1384

Answers (2)

Traycho Ivanov
Traycho Ivanov

Reputation: 3207

You could have a fixture file inside src/test/resources/fixtures/sqs-example.json which represents sqs event as json.

Load the file and deserialize it as SQSEvent using jackson.

 public static <T> T load(String fixture, Class<T> clazz) {
        final ObjectMapper mapper = new ObjectMapper();

        try {
            final String json = loadAsString(fixture);
            return mapper.readValue(json, clazz);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

After that create your MessageListenerHandler instance in your unit test and perform the tests. Context could be mocked for simplicity.

Upvotes: 0

MyNick
MyNick

Reputation: 556

I'll tell you how we work in the company. As general guide, we don't run "unit tests" which use AWS services. You should first test your code without depending on such services. For example, by testing an inner method.

Then, when run "integration tests" which send a message to the relevant queue and wait for a response. For example, by reading from an output queue.

If you do want to test your code in the way you described, you can manually send events that trigger lambdas. Read here: https://docs.aws.amazon.com/lambda/latest/dg/invocation-sync.html

Upvotes: 1

Related Questions