skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search