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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  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.

Wojciech Bulaty user avatar by
Wojciech Bulaty
·
Jan. 30, 23 · Tutorial
Like (5)
Save
Tweet
Share
5.90K 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: support@foxshipping.com
    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.

Popular on DZone

  • Using GPT-3 in Our Applications
  • 3 Main Pillars in ReactJS
  • Introduction to Spring Cloud Kubernetes
  • Shift-Left: A Developer's Pipe(line) Dream?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: