Home > Enterprise >  How should I test a lamdba function with a DynamoDbClient?
How should I test a lamdba function with a DynamoDbClient?

Time:01-13

I'm developing a java lamdba function in plain java. I want to unit test my code but my class contains a DynamoDbClient as private field. What is the recommended way to test this? Can I mock it somehow? Should I put the client in a different class?

private DynamoDbClient amazonDynamoDB;

public String handleRequest(SQSEvent sqsEvent, Context context) {

    this.initDynamoDbClient();
    // logic
}

private void initDynamoDbClient() {
    this.amazonDynamoDB = DynamoDbClient.builder()
            .region(Region.region)
            .build();
}

so far my class looks like this.

CodePudding user response:

It is better to inject the client in the constructor, and do the initialization at the handler level, so you can easily mock any class using the db injection.

CodePudding user response:

You can use singleton pattern and get the unique DynamoDbClient's instantiated client every time you need it

private static DynamoDbClient instance;

public static DynamoDbClient getInstance(){
        if (instance == null) {
            instance = DynamoDbClient.builder()
            .region(Region.region)
            .build();
        }
        return instance;
    }
  • Related