DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Hidden Cost of Flaky Tests in Test Automation
  • Selenium Test Automation Challenges: Common Pain Points and How to Solve Them
  • From Test Automation to Autonomous Quality: Designing AI Agents for Data Validation at Scale
  • End-to-End Test Automation With Playwright, GitHub Page, and Allure Reports

Trending

  • The Missing `bandit` for AI Agents: How I Built a Static Analyzer for Prompt Injection
  • Slopsquatting: Building a Scanner That Catches AI-Hallucinated Packages Before They Reach Production
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial
  • Architecting Zero-Trust AI Agents: How to Handle Data Safely
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. ChatGPT: The Unexpected API Test Automation Help

ChatGPT: The Unexpected API Test Automation Help

ChatGPT can help you generate API tests in REST Assured! This post explores the power of the new AI technology that might disrupt the testing landscape.

By 
Wojciech Bulaty user avatar
Wojciech Bulaty
·
Jan. 30, 23 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
7.9K Views

Join the DZone community and get the full member experience.

Join For Free

ChatGPT can help you generate API tests in REST Assured!

ChatGPT is a type of AI that can comprehend and reply to human input, like a highly intelligent robot you can have a conversation with. Just open an account for free and start chatting with it like with a friend.

Let's begin by requesting ChatGPT to generate an API specification so that we can show how it can also create the tests later on.

Me to ChatGPT: "Create an OpenAPI specification for a tracking API of a new shipping company called FoxShipping."

It generates a sample OpenAPI spec for our new FoxShipping tracking API:

YAML
 
openapi: 3.0.
info:
  title: FoxShipping Tracking API
  version: 1.0.0
  description: This API allows customers to track their shipments with FoxShipping.
  contact:
    name: FoxShipping Support
    email: [email protected]
    url: https://www.foxshipping.com
servers:
  - url: https://api.foxshipping.com/tracking
paths:
  /:
    post:
      summary: Track a shipment with FoxShipping
      operationId: trackShipment
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                trackingNumber:
                  type: string
                  example: 1234567890
                apiKey:
                  type: string
                  example: YOUR_API_KEY
      responses:
        200:
          description: Successful tracking request
          content:
            application/json:
              schema:
                type: object
                properties:
                  trackingNumber:
                    type: string
                    example: 1234567890
                  status:
                    type: string
                    example: "Delivered"
                  estimatedDelivery:
                    type: string
                    format: date-time
                    example: "2022-01-01T12:00:00Z"
        401:
          description: Unauthorized request
        404:
          description: Tracking number not found


Now, we can ask it to create the API tests for it.

Me to ChatGPT: "Write an API test for FoxShipping Tracking API using RestAssured."

Java
 
import io.restassured.RestAssured
import io.restassured.response.Response;
import org.junit.BeforeClass;
import org.junit.Test;


public class FoxShippingTrackingAPITest {
    private static final String API_KEY = "YOUR_API_KEY";
    @BeforeClass
    public static void setup() {
        RestAssured.baseURI = "https://api.foxshipping.com/tracking";
    }


    @Test
    public void testTrackShipment() {
        String trackingNumber = "1234567890";
        String requestBody = "{\"trackingNumber\":\"" + trackingNumber + "\",\"apiKey\":\"" + API_KEY + "\"}";
        Response response = RestAssured.given().
                contentType("application/json").
                body(requestBody).
                when().
                post();
        int statusCode = response.getStatusCode();
        assertEquals(200, statusCode);
        String responseBody = response.getBody().asString();
        assertTrue(responseBody.contains(trackingNumber));
        assertTrue(responseBody.contains("status"));
        assertTrue(responseBody.contains("estimatedDelivery"));
    }
}


Looks decent, but we need to cover the error cases as well. We follow up.

Me to ChatGPT: "Please also add the tests for the error scenarios."

 
import io.restassured.RestAssured
import io.restassured.response.Response;
import org.junit.BeforeClass;
import org.junit.Test;


public class FoxShippingTrackingAPITest {
    private static final String API_KEY = "YOUR_API_KEY";
    @BeforeClass
    public static void setup() {
        RestAssured.baseURI = "https://api.foxshipping.com/tracking";
    }


    @Test
    public void testTrackShipment() {
        String trackingNumber = "1234567890";
        String requestBody = "{\"trackingNumber\":\"" + trackingNumber + "\",\"apiKey\":\"" + API_KEY + "\"}";
        Response response = RestAssured.given().
                contentType("application/json").
                body(requestBody).
                when().
                post();
        int statusCode = response.getStatusCode();
        assertEquals(200, statusCode);
        String responseBody = response.getBody().asString();
        assertTrue(responseBody.contains(trackingNumber));
        assertTrue(responseBody.contains("status"));
        assertTrue(responseBody.contains("estimatedDelivery"));
    }
    
    @Test
    public void testUnauthorizedRequest() {
        String trackingNumber = "1234567890";
        String requestBody = "{\"trackingNumber\":\"" + trackingNumber + "\",\"apiKey\":\"INVALID_API_KEY\"}";
        Response response = RestAssured.given().
                contentType("application/json").
                body(requestBody).
                when().
                post();
        int statusCode = response.getStatusCode();
        assertEquals(401, statusCode);
        String responseBody = response.getBody().asString();
        assertTrue(responseBody.contains("Unauthorized request"));
    }


    @Test
    public void testTrackingNumberNotFound() {
        String trackingNumber = "INVALID_TRACKING_NUMBER";
        String requestBody = "{\"trackingNumber\":\"" + trackingNumber + "\",\"apiKey\":\"" + API_KEY + "\"}";
        Response response = RestAssured.given().
                contentType("application/json").
                body(requestBody).
                when().
                post();
        int statusCode = response.getStatusCode();
        assertEquals(404, statusCode);
        String responseBody = response.getBody().asString();
        assertTrue(responseBody.contains("Tracking number not found"));
    }
}


With that, we now have 3 test cases that cover all 3 scenarios outlined in the FoxShipping Tracking service OpenAPI specification. These serve as a solid foundation for you to use as a starting point and build upon by adding your own customizations and additional test cases.

What other topics related to using ChatGPT in testing would you like to learn more about? Please leave your suggestions in the comments below and I will write about them.

Feel free to follow me on DZone and on LinkedIn for more content like this.

P.S. I generated the image for this article you have seen in the header using DALL-E 2 from OpenAPI by asking it for "an AI entity pair programming with a human developer." It's pretty good!

Please note that it is not recommended to paste your company's private proprietary code into ChatGPT for security reasons unless you have a good reason and permission to do so! This article's purpose is to demonstrate the power of the new AI technology that might disrupt the testing landscape. If you are looking for specific test-generation recipes for your team, feel free to reach out to me directly.

Test automation Testing

Opinions expressed by DZone contributors are their own.

Related

  • The Hidden Cost of Flaky Tests in Test Automation
  • Selenium Test Automation Challenges: Common Pain Points and How to Solve Them
  • From Test Automation to Autonomous Quality: Designing AI Agents for Data Validation at Scale
  • End-to-End Test Automation With Playwright, GitHub Page, and Allure Reports

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook