Reputation: 101
I need help to mock AWS APIs using Mockito in Java. As I have tried to mock RDS connection but connection returns null statement object. I have to mock S3, AWS Data pipeline, JavaSaprkContext
, RDS connection, Lambda, SNS and DynamoDB.
Here is my code for RDS Connection, that returns null statement object:
public void testGetRDSConnection() throws SQLException{
Connection connection = mock(Connection.class);
Statement stmt = null;
stmt = connection.createStatement(); // Get NULL statement Object
ResultSet rs = stmt.executeQuery("SELECT * FROM table");
if (rs.next()) {
System.out.println("+ve Test is PASSED Name = testGetRDSConnection ");
} else {
System.out.println("+ve Test is FAILED Name= testGetRDSConnection ");
}
}
and test case for S3, that return null metadata object:
public void testGetObjectMetadata(){
ObjectMetadata obj = S3Util.getObjectMetadata(mock(AmazonS3Client.class), bucketName, filePath);
if (obj == null) {
System.out.println("+ve Test is FAILED Name= 'testGetObjectMetadata()' No metadata found");
fail("+ve Test is FAILED Name= 'testGetObjectMetadata()' No metadata found");
} else if (obj != null) {
System.out.println("+ve Test is FAILED Name= 'testGetObjectMetadata()'");
}
}
Upvotes: 10
Views: 24025
Reputation: 33511
In addition to whummer's and shachar's answers:
If you're a lucky JUnit 5 user, let me recommend you JUnit 5 extensions for AWS*, a few JUnit 5 extensions that could be useful for testing AWS-related code. These extensions can be used to inject clients for AWS service clients provided by tools like localstack (or the real ones). Both AWS Java SDK v 2.x and v 1.x are supported.
*I maintain this library
Upvotes: 6
Reputation: 497
There are some pretty sophisticated Cloud service mocking frameworks out there, for instance moto has a mock implementation whose functionality is very similar to the actual S3 API.
You could also take a look at LocalStack, a framework which combines existing tools and provides a fully functional local cloud environment that can be used for integration testing.
Although some of these tools are written in other languages (Python, Node.js), it should be easy to spin up the test environment in an external process from your Java test class.
Upvotes: 4
Reputation: 639
Never mock APIs/types that you don't know how they behave. A better solution will be to add your own API that one of its implementation will be AWS. Then you be able to mock your own API
Upvotes: 3