Testing Lambda functions using the AWS Toolkit for Eclipse
In this blog post, I will introduce how to test AWS Lambda functions in Eclipse by using the AWS Toolkit for Eclipse. The AWS Toolkit for Eclipse Lambda Plugin provides a feature in which a JUnit test class is created automatically upon creation of a new AWS Lambda Java project. I will give you step-by-step instructions for creating an AWS Lambda Java project, creating an AWS Lambda function, unit testing the AWS Lambda function, uploading the AWS Lambda function to AWS Lambda, and testing the AWS Lambda function remotely. Currently, AWS Lambda supports five AWS service event sources for Java: S3 Event, SNS Event, Kinesis Event, Cognito Event, and DynamoDB Event. You can also define a custom event. In this post, I will give examples using the S3 Event and a custom event. The other event types can be used in the same way.
Prerequisites
- Install Eclipse version 3.6 (Helios) or later on your computer.
- Follow the instructions on the AWS Toolkit for Eclipse page to Install the AWS Toolkit for Eclipse.
- After it is installed, the new AWS Toolkit for Eclipse icon will appare on the toolbar.
Steps for testing a Lambda function
- Create an AWS Lambda Java project.
- Choose the AWS Toolkit for Eclipse or New icon, and then choose AWS Lambda Java Project.
- When you create a name for the project and package, you should see the corresponding changes in the Preview
S3EventDemo
, Package Name tocom.lambda.demo.s3
, and left the other settings at their defaults.
- The AWS Toolkit for Eclipse will create the following folder structure for the S3 Event.
TheLambdaFunctionHandler
class is an implementation of theRequestHandler
interface that defines the Lambda function you need to implement. TheLambdaFunctionHandlerTest
class is where the unit tests reside. TheTestContext
class is an implementation of theContext
interface, which acts as a parameter for the Lambda function. TheTestUtils
class is a supporting class to parse JSON file. Thes3-event.put.json
file is the sample S3 event source configuration you can use for testing.
- Choose the AWS Toolkit for Eclipse or New icon, and then choose AWS Lambda Java Project.
- Create an AWS Lambda function.
You need to implement the Lambda functionhandleRequest
in theLambdaFunctionHandler
class. It takesS3Event
andContext
as parameters, and returns anObject
. You can always define a custom output class instead of the defaultObject
class. The following is the sample implementation of the Lambda function, which returns a string of the bucket name from the S3 Event.@Override public Object handleRequest(S3Event input, Context context) { context.getLogger().log("Input: " + input); return input.getRecords().get(0).getS3().getBucket().getName(); }
- Unit-test the AWS Lambda function.
In the unit test, theS3Event
parameter is loaded from thes3-event.put.json
file in the tst/ folder and theContext
is implemented and instantiated by the customers for testing. The default unit test in theLambdaFunctionHandlerTest
class is simply printing the output. You may want to change this to a validation as shown in the following code. From thes3-event.put.json
file, the bucket name returned from the Lambda function is expected to be “sourcebucket.”@Test public void testLambdaFunctionHandler() { LambdaFunctionHandler handler = new LambdaFunctionHandler(); Context ctx = createContext(); Object output = handler.handleRequest(input, ctx); if (output != null) { System.out.println(output.toString()); } Assert.assertEquals("sourcebucket", output); }
This is the simplest way to write the test case. When you run the unit test, output like that shown in the following screenshot will appear in the console.
- Upload and run the AWS Lambda function.You can also test the Lambda function after you upload it to AWS Lambda. To do this, right-click anywhere in the workspace of the project, choose Amazon Web Services, and choose Run function on AWS Lambda…, as shown in the following screenshot.
You will be asked to select the JSON file as the
S3Event
input. Choose the default one provided by the AWS Toolkit for Eclipse, as shown in the following screenshot.Choose Invoke. You will see output similar to the following screenshot in the console. The function output is the bucket name returned by the Lambda function.
- Test the custom event Lambda function.
The workflow for testing a custom event is very similar to testing the S3 Event. Let’s define a Lambda function that calculates the maximum value from a list of integer values.- First, define the custom event input class.
public class CustomEventInput { private List<Integer> values; public List<Integer> getValues() { return values; } public void setValues(List<Integer> values) { this.values = values; } }
- Second, define the custom event output class.
public class CustomEventOutput { private Integer value; public CustomEventOutput(int value) { setValue(value); } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } }
- Third, implement the Lambda function.
@Override public CustomEventOutput handleRequest(CustomEventInput input, Context context) { context.getLogger().log("Input: " + input); int maxValue = Integer.MIN_VALUE; for (Integer value : input.getValues()) { if (value > maxValue) { maxValue = value; } } return new CustomEventOutput(maxValue); }
- Fourth, prepare a sample JSON file as the CustomEventInput object for testing. AWS Lambda will use JSON format to represent THE object you defined. Here is an example using POJOs for handler input/output.
{ "values" : [34, 52, 335, 32] }
- Lastly, upload this Lambda function to AWS Lambda, and test remotely. You should see console output similar to the following. The output is the JSON format of the CustomEventOutput object returned by the Lambda function.
- First, define the custom event input class.
This is how a typical Lambda function is written and tested using the AWS Toolkit for Eclipse. For more advanced use cases, you can use the S3 Event and DynamoDB Event examples provisioned by AWS Lambda.
相關推薦
Testing Lambda functions using the AWS Toolkit for Eclipse
In this blog post, I will introduce how to test AWS Lambda functions in Eclipse by using the AWS Toolkit for Eclipse. The AWS Toolkit for Eclipse
AWS Toolkit for Eclipse
Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So
AWS Toolkit for eclipse Java 開發以及Amazon S3使用簡單介紹
前陣子為了將AWS Lambda function 從VS上.NET遷移至Linux系統,所以選擇以前使用過的Eclipse搭配Java語言來實現。 進入主題,首先我們需要按照官方的說明安裝好Eclipse Java EE和AWS Toolkit,官方引導
Using the AWS Lambda Project in Visual Studio
Last week we launched C# and .NET Core support for AWS Lambda. That release provided updated tooling for Visual Studio to help you get started wri
Administrating AWS resources productively using the AWS CLI
Administrating AWS resources productively using the AWS CLII’ll bet you’ve already got some stuff running on AWS and you made it happen using the browser c
Introducing support for Amazon S3 Select in the AWS SDK for PHP
We’re excited to announce support for the Amazon Simple Storage Service (Amazon S3) SelectObjectContent API with event streams in the AWS SDK for
Advanced client stubbing in the AWS SDK for Ruby Version 3
The AWS SDK for Ruby provides a robust set of features for stubbing your clients, to make unit tests easier and less fragile. Many of you have use
Configure Geoproximity Routing Using the AWS CLI
{ "AWSPolicyFormatVersion":"2015-10-01", "RecordType":"A", "StartRule":"geoprox-rule", "Endpoints":{ "aws-us-west-1-region":{
Pass Multiple Values to a List Parameter Type Using the AWS CLI create
{ "AWSTemplateFormatVersion" : "2010-09-09", "Parameters" : { "VpcId" : { "Type" : "AWS::EC2::VPC::Id", "Description"
Configure Service Discovery with Route 53 Auto Naming Using the AWS CLI
{ "Service": { "DnsConfig": { "NamespaceId": "ns-f2wjnv2p7pqtz5f2", "DnsRecords": [ {
Create Alias Resource Record Sets in Route 53 Using the AWS CLI
{ "Comment": "Alias record for S3 bucket", "Changes": [{ "Action": "CREATE", "ResourceRecor
Create a VPC Using the AWS Management Console
Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So
Create a Virtual Tape Library Using the AWS Storage Gateway
The AWS Storage Gateway connects an on-premises software appliance with cloud-based storage to integrate your on-premises IT environment with the
Assume an IAM Role Using the AWS CLI
Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So
Provision AWS Services Through Kubernetes Using the AWS Service Broker
IMPORTANT NOTE – Oct 12, 2018 The steps described in this post are no longer accurate, please refer to the AWS Service Broker Git
Create a Simple Resource Record Set in Amazon Route 53 Using the AWS CLI
{ "Comment": "CREATE/DELETE/UPDATE", "Changes": [ { "Action": "CREATE",
Troubleshoot Errors with Creating Amazon Route 53 Resource Record Sets Using the AWS CLI
An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation: RRSet of type CNAME with DNS name domain.com. is no
Get Started with Deep Learning Using the AWS Deep Learning AMI
Whether you’re new to deep learning or want to build advanced deep learning projects in the cloud, it’s easy to get started by using AWS.
Alibaba Cloud Toolkit for Eclipse & ECS、EDAS 或容器服務 Kubernetes
3.3 iyu common .html log 阿裏雲 後臺管理 paas mscs UserGuide_V2.1.0http://toolkit.aliyun.com/eclipse/?spm=5176.2020520130.105.3.3c3b697bOHma9f&a
Install the AWS CLI Using the Bundled Installer (Linux, macOS, or Unix)
On Linux, macOS, or Unix, you can also use the bundled installer to install the AWS CLI. The bundled installer includes all dependencies and can be used of