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()'");
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With