Search code examples
postgresqlrest-assuredserenity-bddcucumber-serenity

Connect to Database through rest assured (REST API automation)


We are automating testing of REST APIs using serenity-rest-assured. A requirement is to connect to a PostgreSQL database and compare the GET API call values with the database table values.

I searched over the internet and couldn't find an answer. I may not be using the right search keywords.

Please guide, can it be done connecting to DB and test the API result?


Solution

  • Just tried it out, The below is enough to prove that you can get the values from the database and validate against the values you get as a part of your Rest Assured implementation.

    This is a small piece of code which serves the purpose and you can improvise it based on your requirement

    Here's my class and I hope the code is self explanatory

      public class S_62551943 {
    
        // Declaration of the variables
        
        private final String url = "jdbc:postgresql://localhost/dvdrental";
        private final String user = "postgres";
        private final String password = "root";
        public static String fname = null;
    
        // Method to initalize connection to the database and execute query
        
        public void connect() {
    
            try {
                Connection conn = DriverManager.getConnection(url, user, password);
                {
                    if (conn != null) {
    
                        PreparedStatement pst = conn.prepareStatement("select first_name from actor where last_name = 'Lollobrigida'");
                        ResultSet rs = pst.executeQuery();
                        {
                            while (rs.next()) {
    
                                fname = rs.getString("first_name");
                                System.out.println("The value from the table is : "+fname);
                            }
                        }
    
                    } else
                        System.out.println("Failed to connect");
                }
    
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
    
        // Main method and Rest Assured Code
        
        public static void main(String[] args) {
            S_62551943 app = new S_62551943();
            app.connect();      
            given().when().get("https://reqres.in/api/users/2").then().body("data.first_name", equalToIgnoringCase(fname));
            System.out.println("Execution Successful");
        }
    
    }
    

    More information on Postgres - https://www.postgresqltutorial.com/