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
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.
You can use singleton pattern and get the unique DynamoDbClient’s instantiated client every time you need it