Test Ready Lambda Functions
To enable easy testing of our serverless applications there are some slight tweaks to make to our Lambda function. Instead of having a single constructor and performing all of our initiailization there, we are leveraging an internal constructor and dependency injection to give us a flexible easy to test function.
The Default Constructor
Remember, the Lambda service always needs a public, parameterless constructor. Without this, the Lambda service won't be able to initialize your handler class.
An internal constructor
All of our initialization logic is seperated into an internal constructor. Notice how the public constructor Lambda will use calls out internal constructor, passing in null values for the services required.
This gives us an entrypoint in which we can pass in mock implementations of our services to test how the logic of our Lambda functions functions with different event payloads.
Dependency Injection
When deployed, the handler will be null. The function code will then fall back to the Startup.ServiceProvider
dependency injection container and load the ListStorageAreasQueryHandler
service. This gives us further control of how an application will run both under test and in the cloud.
Configuring Dependency Injection
A quick peek at the Startup class. A lazy loaded ServiceProvider
means that dependency injection will only be setup if required. If we had another Lambda function in our application that didn't require any of these services, this setup would never run.
The Default Constructor
Remember, the Lambda service always needs a public, parameterless constructor. Without this, the Lambda service won't be able to initialize your handler class.
An internal constructor
All of our initialization logic is seperated into an internal constructor. Notice how the public constructor Lambda will use calls out internal constructor, passing in null values for the services required.
This gives us an entrypoint in which we can pass in mock implementations of our services to test how the logic of our Lambda functions functions with different event payloads.
Dependency Injection
When deployed, the handler will be null. The function code will then fall back to the Startup.ServiceProvider
dependency injection container and load the ListStorageAreasQueryHandler
service. This gives us further control of how an application will run both under test and in the cloud.
Configuring Dependency Injection
A quick peek at the Startup class. A lazy loaded ServiceProvider
means that dependency injection will only be setup if required. If we had another Lambda function in our application that didn't require any of these services, this setup would never run.
A final note, you'll need to add the below code to an AssemblyInfo.cs
file in your Lambda function project. This allows a unit test project to access and use the internal constructor.
Further Reading
- The AWS Samples GitHub organisation contains a serverless-test-samples repository