Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock AWS API using Mockito in java

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()'");

    }
}
like image 927
aqsa93 Avatar asked Jun 21 '16 18:06

aqsa93


1 Answers

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

like image 94
madhead - StandWithUkraine Avatar answered Sep 18 '22 14:09

madhead - StandWithUkraine