Testing a Lambda function 

To test the Lambda function that we wrote and uploaded in the preceding sections, we have to create a test harness via the Configure Test Event drop-down menu in the header. This test will happen in isolation (think of it as a sandbox mode). We have not wired it up to any of the event sources just yet.

The following screenshots show the process, which can be described as follows:

  1. Select the drop-down menu to configure a new test event:

Initial step
  1. Configure the test events. First, let's configure a positive scenario, where a valid input is given, as follows:
Test event for positive flow is created

A few points should be noted, as follows:

  1. Create a new test event from a template.
  2. Name the event testGreeterService.
  3. Add the value for this invocation. This is an important part of setting up a test harness. As described earlier, this maps to the InputType parameter that is passed to the function. This harness accepts a JSON object, and it's incumbent on the developer to specify the value properly, so that it gets marshaled to the InputType.

In our example, we have assumed that the input type is a java.lang.String, and hence, we specify one. For more complex and nested types, one has to add the value accordingly.

Let's create a test event for the negative scenario of the preceding template where in we provide an input which will break the function. The following screenshot shows how to configure the test event for a negative flow:

Note that instead of giving a string value, we have used a simple JSON string, which can't be parsed, because our handler just accepts the string.

  1. Click on Create and then the Save button and invoke the function with the test events that were created by clicking on Test. The output is shown in the following screenshot:

Note the output,  Hello, Lambda, which is as per our expectations.

The following screenshot shows the negative test event execution:

Note that the JSON deserialization fails. In a production-grade Lambda function, this error has to be handled gracefully, and appropriate actions need to be taken. In this book, it is left out for simplicity's sake.

This concludes the basics of creating, configuring, and testing a Lambda function via the console. In the following sections, we'll take a look at wiring it up to an upstream component, like an API Gateway, so that we will have an end-to-end working example of a simple (but production-grade) Lambda function.