Master-Level API Test Automation Labs

PostmanSoapUICI/CDSecurityData-Driven

Mindset: No fluff. When something fails, read the error and fix it. That’s how senior testers are forged.

Postman Labs

Lab 1 — API Smoke Testing (REST)

Goal: Validate availability, basic contract, and latency.

  1. Install & Setup
    • Install Postman (Desktop).
    • Create a WorkspaceCollection named Ecommerce-Smoke.
  2. Import API
    • Import via Link: https://petstore.swagger.io/v2/swagger.json (or any public Swagger).
    • Save endpoints you’ll use into Ecommerce-Smoke.
  3. Create Environment
    • Create environment Dev with variables:
      • baseUrl = https://petstore.swagger.io/v2
      • timeoutMs = 500
  4. Write Tests (Request → Tests tab)
    pm.test("Status is 200", () => pm.response.to.have.status(200));
    pm.test("Responds under threshold", () => pm.expect(pm.response.responseTime).to.be.below(+pm.environment.get("timeoutMs")));
    pm.test("Body has expected keys", () => {
      const json = pm.response.json();
      pm.expect(json).to.be.an("array"); // adapt to endpoint
    });
  5. Run Smoke
    • Use Collection Runner → Env: Dev → Run.
    • Exit criteria: Any status ≠ 2xx, schema mismatch, or response time > threshold is a fail. Fix or flag.

Lab 2 — Data-Driven Testing

Goal: Parameterize tests with CSV/JSON and assert variant outcomes.

  1. Create Data File logins.csv
    username,password,expectedStatus
    validUser,correct,200
    validUser,wrong,401
    unknown,any,404
  2. Request & Variables
    • POST {{baseUrl}}/user/login

    Body (raw JSON):

    { "username": "{{username}}", "password": "{{password}}" }
  3. Tests
    pm.test("Status matches expected", () => {
      const expected = +pm.iterationData.get("expectedStatus");
      pm.expect(pm.response.code).to.eql(expected);
    });
  4. Run
    • Collection Runner → Select logins.csv → Run.
    • Exit criteria: Mismatch between actual and expected status ⇒ defect or spec update.

Lab 3 — API Chaining (Create → Read → Update → Delete)

Goal: Carry state across requests via variables.

  1. Requests in Order
    • POST {{baseUrl}}/user (create)
    • GET {{baseUrl}}/user/{{username}} (read)
    • PUT {{baseUrl}}/user/{{username}} (update)
    • DELETE {{baseUrl}}/user/{{username}} (delete)
  2. Create → Save IDs (Tests)
    const body = pm.response.json();
    pm.environment.set("username", body.username || "john.doe");
    pm.environment.set("userId", body.id || 0);
    pm.test("Created", ()=> pm.expect(pm.response.code).to.be.oneOf([200,201]));
  3. GET → Assert body uses saved data
    pm.test("Correct user returned", () => {
      const json = pm.response.json();
      pm.expect(json.id).to.eql(+pm.environment.get("userId"));
    });
  4. PUT → Change a field
    • Body: update firstName, lastName.
    • Tests: assert changed field reflected.
  5. DELETE → Verify deletion
    • After DELETE, run GET expecting 404.

Lab 4 — Authentication Automation (Basic, OAuth2, JWT)

Goal: Automate token retrieval and header injection.

  1. Basic Auth
    • In Auth tab: Type Basic Auth; verify Authorization header is auto-set.
    • Test 401 for bad creds.
  2. OAuth 2.0 (Client Credentials or Auth Code)
    • Create a request POST {{authBase}}/oauth/token with form-data:
      • grant_type=client_credentials, client_id, client_secret, scope

    Tests:

    const json = pm.response.json();
    pm.environment.set("access_token", json.access_token);
    pm.test("Token acquired", ()=> pm.expect(json.access_token).to.exist);

    Pre-request Script for protected requests:

    pm.request.headers.upsert({ key: "Authorization", value: `Bearer ${pm.environment.get("access_token")}` });
  3. JWT Refresh Flow
    • Add a request to refresh token when 401 occurs:
    if (pm.response.code === 401) {
      postman.setNextRequest("Refresh Token"); // name of your refresh request
    }
    • Refresh request sets new access_token, then setNextRequest(null) to resume.

Lab 5 — Regression Suite + Newman + CI/CD

Goal: Turn your collection into a headless, pipeline-ready suite.

  1. Stabilize Collection
    pm.environment.set("rand", Math.floor(Math.random()*1e6));
  2. Export
    • Export Collection (.json) and Environment (.postman_environment.json) into a repo.
  3. Newman Local Run
    npm i -g newman
    newman run Ecommerce-Smoke.postman_collection.json \
      -e Dev.postman_environment.json \
      --reporters cli,junit --reporter-junit-export reports/junit.xml
  4. GitHub Actions (example)
    name: postman-regression
    on: [push, workflow_dispatch]
    jobs:
      run-newman:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-node@v4
            with: { node-version: '20' }
          - run: npm i -g newman
          - run: |
              newman run Ecommerce-Smoke.postman_collection.json \
              -e Dev.postman_environment.json \
              --reporters cli,junit --reporter-junit-export reports/junit.xml
  5. Exit Gates
    • Fail build if any test fails or if average response time > 2000 ms (enforce timing in Postman tests and rely on Newman exit code in CI).

SoapUI Labs

Lab 1 — WSDL Import & Basic Requests

Goal: Get comfortable with SOAP structure.

  1. Create Project
    • File → New SOAP Project → Name: CountryInfo.
    • Initial WSDL: http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL
  2. Generate Requests
    • SoapUI creates operations under the service. Open ListOfCountryNamesByName request.
  3. Send & Verify
    • Click Submit.
    • Check response for <ListOfCountryNamesByNameResult> presence.
  4. Schema Compliance
    • Right-click project → Check WS-I Compliance (if available) and note violations.

Lab 2 — Assertions & Property Transfers

Goal: Validate XML precisely and pass data between steps.

  1. XPath Assertion
    boolean(//m:ListOfCountryNamesByNameResult)

    Expected: true (use XPath Tester dialog to evaluate).

  2. Value Assertion
    //m:tCountryCodeAndName[1]/m:sName/text()

    Expected: Not empty.

  3. Property Transfer
    • Create TestSuite → TestCase.
    • Step 1: ListOfCountryNamesByName.
    • Step 2: FullCountryInfo.
    • Add Property Transfer: Map tCountryCodeAndName[1]/m:sISOCode from Step 1 response → Step 2 request node.

Lab 3 — Data-Driven SOAP Tests

Goal: Iterate requests from CSV/Excel.

  1. Add DataSource
    • TestCase → Add Step → DataSource.
    • Type: CSV; file countries.csv:
    ISO
    US
    GB
    JP
  2. Bind to Request
    • In FullCountryInfo request, reference ${#DataSource#ISO} in the ISO parameter.
  3. Loop
    • Add DataSource Loop pointing from DataSourceFullCountryInfo and back.
  4. Assertions
    • Add XPath assertion that currency or capital is not empty for each ISO.

Lab 4 — Security Testing (Negative & Fuzz)

Goal: Prove the service fails safely.

  1. Create Security Test
    • Right-click TestSuite → New Security Test.
  2. Add Scans
    • Invalid Types, Malformed XML, SQL Injection, XPath Injection.
    • Configure payloads (e.g., ' OR '1'='1 in string fields).
  3. Run & Review
    • Run with 10 threads for 2 minutes.
    • Verify: APIs return 4xx/5xx without stack traces, no sensitive info in faults, response times stable.

Lab 5 — Mocking & Load Testing

Goal: Break dependencies and test performance.

  1. Create MockService
    • Right-click Service → Generate MockService.
    • For operation(s), define static responses (OK and Fault variants).
  2. Point Requests to Mock
    • Change endpoint to the mock’s URL.
    • Verify contract compliance continues.
  3. Load Test
    • Right-click a TestCase → New LoadTest.
    • Strategy: Simple; Threads: 50; Limit: 2 minutes.
    • Run; capture Avg/95th percentile latency; error rate.
  4. Export Reports
    • LoadTest Report to CSV/PDF for baseline.

Capstone Labs (Enterprise-Grade)

Capstone 1 — Insurance Policy Management (SOAP + REST)

Goal: Cross-tech workflow with real gates.

  1. Design Flow
    • SOAP: CreatePolicy → returns PolicyNumber.
    • REST: POST /payments with PolicyNumber → returns paymentId.
    • REST: GET /policies/{PolicyNumber} → expect status Active.
  2. SoapUI
    • Import WSDL; TestCase with CreatePolicy.
    • Transfer PolicyNumber to Properties at TestSuite level.
  3. Postman
    • Environment var policyNumber pulled from SoapUI output (shared file or fixture).
    • POST /payments uses {{policyNumber}}.
    • GET /policies/{{policyNumber}} asserts state.
  4. Automation
    • Run SoapUI (testrunner.sh) → output JSON with policyNumber.
    • Run Newman with that variable injected (--env-var policyNumber=...).
    • Exit criteria: Any failed assertion or final state ≠ Active fails the job.

Capstone 2 — Microservices E2E + Concurrency

Goal: Orchestrate many REST services; simulate load.

  1. Services
    • Auth → Catalog → Cart → Checkout → Orders.
  2. Postman Collection
    • Chain all steps; generate random SKU/user per run.
  3. Concurrency
    docker run --rm -v "$PWD":/etc/newman postman/newman \
      run e2e.postman_collection.json -e dev.env.json --iteration-count 100
  4. SLO Checks
    • Each request asserts < 800 ms; p95 target displayed in report.

Capstone 3 — CI/CD with Quality Gates

Goal: Nightly runs with hard failure rules.

  1. Store Collections & SoapUI Projects in Git
  2. Jenkins
    • Pipeline: Checkout → Run SoapUI testrunner.sh → Run Newman → Archive JUnit.
  3. Gates
    • Build fails if:
      • Any test fails
      • p95 latency > 2s
      • Error rate > 2%
  4. Trend
    • Publish historical charts; investigate regressions before release.

🔹 Master Test Automation Plan (Web + API)

1. Test Strategy

Scope:

Tools: Selenium (UI), Postman/SoapUI (API), TestNG/JUnit (runner), Jenkins/GitHub Actions (CI/CD).

Reporting: Unified reports in Excel/CSV, with pass/fail, defect metrics, and trends.

Approach:

2. Test Case Design

Create test cases in Excel with unified format:

Test ID Type Scenario Steps Expected Result Status Comments
UI001 Web Login via UI 1. Open browser → 2. Enter creds → 3. Click login User redirected to dashboard
UI002 Web Add product to cart Navigate to product page → Add to cart Product appears in cart
API001 API Login endpoint valid Send POST /login Returns token
API002 API Checkout with empty cart POST /checkout with no items 400 Bad Request

3. Execution Flow

  1. API Layer First
    • Run Postman/SoapUI regression suite.
    • Validate business logic and data flow.
    • Export results → CSV.
  2. UI Layer (Selenium)
    • Run Selenium suites (TestNG/JUnit).
    • Validate end-to-end workflows.
    • Export results → CSV/HTML.
  3. Reporting & Metrics
    • Merge Postman/SoapUI + Selenium results into Excel dashboard.
    • Metrics: Pass/Fail % by type, Defect severity distribution, Execution trend.

4. Automation Framework Structure

/automation-framework
  ├── /api-tests         (Postman collections, SoapUI projects)
  ├── /ui-tests          (Selenium test scripts)
  ├── /test-data         (Excel/CSV input files)
  ├── /reports           (execution results)
  ├── /utils             (common libraries: logger, db, api client)
  └── pom.xml            (if using Maven)
    

5. CI/CD Integration

Use Jenkins pipeline (or GitHub Actions):

  1. Run Postman collection (newman CLI).
  2. Run SoapUI suite (testrunner CLI).
  3. Run Selenium tests.
  4. Consolidate results → push to Excel/CSV report.

6. Lab Exercises

🔹 Excel Template for Automation Testing

Here’s your ready-to-use Excel template for automation testing with Selenium + API.

📥 Download Automation Test Cases Template

Included in the Template:


import pandas as pd

# Create sample test case data for API + Selenium
data = {
    "Test ID": ["API001", "API002", "UI001", "UI002"],
    "Type": ["API", "API", "Web", "Web"],
    "Scenario": [
        "Login endpoint valid",
        "Checkout with empty cart",
        "Login via UI",
        "Add product to cart"
    ],
    "Steps": [
        "POST /login with valid creds",
        "POST /checkout with no items",
        "Open browser → enter creds → click login",
        "Navigate to product → click add to cart"
    ],
    "Expected Result": [
        "Returns token",
        "400 Bad Request",
        "User redirected to dashboard",
        "Product appears in cart"
    ],
    "Actual Result": ["", "", "", ""],
    "Status": ["", "", "", ""],
    "Comments": ["", "", "", ""]
}

# Convert to DataFrame
df = pd.DataFrame(data)

# Add sample formulas for Excel reporting (e.g., pass rate)
report_data = {
    "Metric": ["Total Tests", "Passed", "Failed", "Pass Rate %"],
    "Formula": [
        "=COUNTA(TestCases!A2:A100)", 
        '=COUNTIF(TestCases!G2:G100,"Pass")',
        '=COUNTIF(TestCases!G2:G100,"Fail")',
        '=B2/B1*100'
    ]
}
report_df = pd.DataFrame(report_data)

# Save to Excel with two sheets
excel_path = "Automation_Test_Cases_Template.xlsx"
with pd.ExcelWriter(excel_path, engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='TestCases', index=False)
    report_df.to_excel(writer, sheet_name='Report', index=False)

print("Excel file saved at:", excel_path)
    

You can directly plug in results from Postman, SoapUI, or Selenium runs into the template to track execution and reporting seamlessly.

What to Hand In (Old-School Discipline, Modern Stack)