Unit Test the Application

With the unit test of the application we perform automated test of the application without the infrastructure. This can be done with mocked AWS calls like shown in Chapter Test using reflection or basic functions like in this example.

The application shall handle an S3 put event, so at first we generate this event and store the json. See the put event in architectures/serverless/app/test/put.json

As we only need the S3 object key from the S3 event, we write a function ExtractKey.

Testing event based functions

There are four basic steps:

  1. Read testevent
  2. Unmarshal event to structure
  3. Call tested function with event structure
  4. Call assertions

1 Read testevent

	const testfile = "test/put.json"
	jsonFile, err := os.Open(testfile)
	if err != nil {
		fmt.Println(err)
		panic(err)
	}
	fmt.Println("Successfully Opened ", testfile)
	defer jsonFile.Close()
  byteValue, _ := ioutil.ReadAll(jsonFile)
	if err != nil {
		print(err)
	}

This part is quite the same most of the time. Don’t skip the if err parts, sometimes you have the wrong filepath etc etc.

2 Unmarshal event to structure

	var s3event events.S3Event;
	err = json.Unmarshal([]byte(byteValue), &s3event)

The events are defined in github aws-lambda-go/events/. If your event is not defined, use an online json to struct website to define your own structure.

3 Call tested function with event structure

realKey := dsl.ExtractKey(s3event);

4 Call assertion

	expectedKey := "my2etestkey.txt"
	assert.Equal(t, expectedKey,realKey)

The key must be the same as in the event to make the test PASS:

{
   "Records": [
     {
...
       "s3": {
...
         "object": {
           "key": "my2etestkey.txt",

You can guess the tested function code from the json hierarchy…

Motivation

Again, the first time it may seem like a testing overkill. But the effort is not so much and you get in return:

  • Protection against typos in the json path
  • Possibility to handle different files
  • You prove that your function is working correctly
  • In mode complex json structures it is not so obvious where the attribute is hidden

In the next chapter the integration and end2end test are described.

Source

See the full source on github.

Sources