A comprehensive, production-ready API testing framework built with Java, REST Assured, TestNG, and Maven. This framework provides a robust foundation for API testing with features like data-driven testing, parallel execution, detailed reporting, and CI/CD integration.
- REST API Testing: Comprehensive HTTP methods support (GET, POST, PUT, DELETE, PATCH)
- Authentication: Multiple auth methods (Basic, Bearer Token, OAuth2, API Key)
- Request/Response Validation: Schema validation, response assertions, data extraction
- Data-Driven Testing: Excel, CSV, JSON, and database-driven test data
- Parallel Execution: TestNG parallel execution with thread safety
- Environment Management: Multi-environment configuration support
- Request/Response Logging: Detailed logging with configurable levels
- Test Data Management: Faker integration for dynamic test data generation
- Database Integration: Support for MySQL, PostgreSQL, MongoDB
- File Upload/Download: Multipart form data and file handling
- Performance Testing: Response time validation and performance metrics
- Mock Server Integration: WireMock integration for testing
- Retry Mechanism: Configurable retry logic for flaky tests
- ExtentReports: Rich HTML reports with screenshots and logs
- Allure Reports: Interactive test reporting with history
- TestNG Reports: Native TestNG HTML and XML reports
- Custom Listeners: Test execution listeners for monitoring
- Slack Integration: Test results notifications
- Email Reports: Automated email notifications
- Jenkins: Complete Jenkins pipeline configuration
- GitHub Actions: Automated workflow configuration
- Docker: Containerized test execution
- Maven: Build lifecycle management
- Quality Gates: SonarQube integration for code quality
java-rest-assured-api-testing-framework/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── framework/
│ │ │ ├── config/
│ │ │ │ ├── Configuration.java
│ │ │ │ ├── Environment.java
│ │ │ │ └── TestDataConfig.java
│ │ │ ├── core/
│ │ │ │ ├── BaseTest.java
│ │ │ │ ├── APIClient.java
│ │ │ │ ├── RequestBuilder.java
│ │ │ │ └── ResponseValidator.java
│ │ │ ├── utils/
│ │ │ │ ├── DataGenerator.java
│ │ │ │ ├── FileUtils.java
│ │ │ │ ├── DatabaseUtils.java
│ │ │ │ ├── JsonUtils.java
│ │ │ │ └── ExcelUtils.java
│ │ │ ├── models/
│ │ │ │ ├── User.java
│ │ │ │ ├── Product.java
│ │ │ │ └── Order.java
│ │ │ ├── listeners/
│ │ │ │ ├── TestListener.java
│ │ │ │ ├── RetryAnalyzer.java
│ │ │ │ └── SlackNotifier.java
│ │ │ └── reporting/
│ │ │ ├── ExtentManager.java
│ │ │ ├── ReportUtils.java
│ │ │ └── AllureUtils.java
│ │ └── resources/
│ │ ├── config/
│ │ │ ├── application.properties
│ │ │ ├── dev-config.properties
│ │ │ ├── test-config.properties
│ │ │ └── prod-config.properties
│ │ ├── schemas/
│ │ │ ├── user-schema.json
│ │ │ ├── product-schema.json
│ │ │ └── order-schema.json
│ │ ├── test-data/
│ │ │ ├── users.xlsx
│ │ │ ├── products.csv
│ │ │ └── test-scenarios.json
│ │ └── logback.xml
│ └── test/
│ ├── java/
│ │ └── com/
│ │ └── tests/
│ │ ├── api/
│ │ │ ├── UserApiTests.java
│ │ │ ├── ProductApiTests.java
│ │ │ ├── OrderApiTests.java
│ │ │ └── AuthenticationTests.java
│ │ ├── integration/
│ │ │ ├── WorkflowTests.java
│ │ │ └── EndToEndTests.java
│ │ ├── performance/
│ │ │ └── PerformanceTests.java
│ │ └── smoke/
│ │ └── SmokeTests.java
│ └── resources/
│ ├── testng.xml
│ ├── testng-parallel.xml
│ ├── testng-smoke.xml
│ └── allure.properties
├── docker/
│ ├── Dockerfile
│ └── docker-compose.yml
├── scripts/
│ ├── run-tests.sh
│ ├── run-smoke-tests.sh
│ └── generate-reports.sh
├── .github/
│ └── workflows/
│ └── ci-cd.yml
├── jenkins/
│ └── Jenkinsfile
├── pom.xml
├── README.md
└── .gitignore
- Java: JDK 11 or higher
- Maven: 3.6.0 or higher
- IDE: IntelliJ IDEA or Eclipse (optional)
- Git: Version control system
git clone https://github.com/demo/java-rest-assured-api-testing-framework.git
cd java-rest-assured-api-testing-framework
mvn clean install -DskipTests
# Copy configuration template
cp src/main/resources/config/application.properties.template src/main/resources/config/application.properties
# Edit configuration
nano src/main/resources/config/application.properties
# Run smoke tests
mvn clean test -Dsuite=smoke
# Run all tests
mvn clean test
# Run specific test class
mvn clean test -Dtest=UserApiTests
import com.framework.core.BaseTest;
import com.framework.core.APIClient;
import io.restassured.response.Response;
import org.testng.annotations.Test;
public class QuickStartTest extends BaseTest {
@Test
public void testGetUser() {
Response response = APIClient.getInstance()
.get("/users/1")
.then()
.statusCode(200)
.extract().response();
// Validate response
assertThat(response.jsonPath().getString("name")).isNotNull();
}
@Test
public void testCreateUser() {
String requestBody = """
{
"name": "John Doe",
"email": "john@example.com",
"phone": "1234567890"
}
""";
Response response = APIClient.getInstance()
.post("/users", requestBody)
.then()
.statusCode(201)
.extract().response();
// Validate created user
assertThat(response.jsonPath().getString("id")).isNotNull();
}
}
@Test(dataProvider = "userData")
public void testCreateUserWithData(String name, String email, String phone) {
User user = User.builder()
.name(name)
.email(email)
.phone(phone)
.build();
Response response = APIClient.getInstance()
.post("/users", user)
.then()
.statusCode(201)
.extract().response();
// Validate response
assertThat(response.jsonPath().getString("email")).isEqualTo(email);
}
@DataProvider(name = "userData")
public Object[][] userData() {
return ExcelUtils.getTestData("users.xlsx", "UserData");
}
@Test
public void testUserSchemaValidation() {
APIClient.getInstance()
.get("/users/1")
.then()
.statusCode(200)
.body(matchesJsonSchema(getSchema("user-schema.json")));
}
- Centralized HTTP client with request/response handling
- Authentication management
- Request/response logging
- Error handling and retry logic
- Common test setup and teardown
- Test data management
- Reporting integration
- Configuration management
- Fluent API for building requests
- Header management
- Query parameter handling
- Request body serialization
- Response assertion utilities
- Schema validation
- Data extraction helpers
- Performance validation
The framework supports multiple environments with centralized configuration:
# application.properties
base.url=https://api.example.com
auth.type=bearer
auth.token=${AUTH_TOKEN}
timeout.connection=30000
timeout.read=60000
retry.count=3
retry.delay=1000
// Read test data from Excel
Object[][] testData = ExcelUtils.getTestData("users.xlsx", "UserData");
// Write test results to Excel
ExcelUtils.writeTestResults("results.xlsx", testResults);
// Load test data from JSON
List<User> users = JsonUtils.loadTestData("users.json", User.class);
// Generate dynamic test data
User user = DataGenerator.generateUser();
Basic functionality validation:
- Health check endpoints
- Authentication tests
- Critical path validation
Comprehensive API testing:
- CRUD operations
- Input validation
- Error handling
- Edge cases
Cross-service testing:
- Workflow validation
- Data consistency
- Service dependencies
Response time validation:
- Latency testing
- Throughput testing
- Stress testing
@Test
public void testUserFromDatabase() {
// Get user from database
User dbUser = DatabaseUtils.getUserById(1);
// Validate via API
Response response = APIClient.getInstance()
.get("/users/" + dbUser.getId())
.then()
.statusCode(200)
.extract().response();
// Compare data
assertThat(response.jsonPath().getString("name")).isEqualTo(dbUser.getName());
}
@Test
public void testFileUpload() {
File file = new File("test-file.pdf");
Response response = APIClient.getInstance()
.multipart("file", file)
.post("/upload")
.then()
.statusCode(200)
.extract().response();
assertThat(response.jsonPath().getString("filename")).isEqualTo("test-file.pdf");
}
@Test
public void testOAuth2Authentication() {
String token = AuthUtils.getOAuth2Token("client_id", "client_secret");
Response response = APIClient.getInstance()
.auth(token)
.get("/protected-resource")
.then()
.statusCode(200)
.extract().response();
}
Rich HTML reports with:
- Test execution timeline
- Request/response details
- Screenshots and logs
- Test categorization
Interactive reports with:
- Test history
- Trend analysis
- Test categorization
- Attachments
@Test
public void testWithCustomReporting() {
ExtentTest test = ExtentManager.createTest("User API Test");
try {
Response response = APIClient.getInstance()
.get("/users/1")
.then()
.statusCode(200)
.extract().response();
test.pass("API call successful");
test.info("Response: " + response.asString());
} catch (Exception e) {
test.fail("Test failed: " + e.getMessage());
throw e;
}
}
pipeline {
agent any
stages {
stage('Test') {
steps {
sh 'mvn clean test'
}
}
stage('Reports') {
steps {
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: 'target/reports',
reportFiles: 'index.html',
reportName: 'Test Report'
])
}
}
}
}
name: API Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@v2
with:
java-version: '11'
distribution: 'temurin'
- name: Run tests
run: mvn clean test
- name: Generate reports
run: mvn allure:report
# Build Docker image
docker build -t api-tests .
# Run tests
docker run --rm -v $(pwd)/target:/app/target api-tests
# Run with environment variables
docker run --rm -e BASE_URL=https://api.staging.com api-tests
version: '3.8'
services:
api-tests:
build: .
environment:
- BASE_URL=https://api.example.com
- AUTH_TOKEN=${AUTH_TOKEN}
volumes:
- ./target:/app/target
- Group related tests in test classes
- Use descriptive test names
- Implement proper test data cleanup
- Use test categories for different test types
- Use external test data files
- Implement data generators for dynamic data
- Clean up test data after execution
- Use database transactions for data isolation
- Implement comprehensive error handling
- Use custom exceptions for better error messages
- Log detailed error information
- Implement retry mechanisms for flaky tests
- Use parallel execution for faster test runs
- Implement connection pooling
- Cache authentication tokens
- Use efficient data structures
- Keep dependencies updated
- Regular code reviews
- Implement code quality checks
- Monitor test execution metrics
// Increase timeout values
APIClient.getInstance()
.timeout(60000)
.get("/endpoint");
// Verify token validity
String token = AuthUtils.refreshToken();
APIClient.getInstance().auth(token);
// Debug schema validation
Response response = APIClient.getInstance().get("/users/1");
System.out.println("Response: " + response.asString());
System.out.println("Schema: " + getSchema("user-schema.json"));
# Enable debug logging
mvn clean test -Dlog.level=DEBUG
# Run single test with debug
mvn clean test -Dtest=UserApiTests#testGetUser -Ddebug=true
- Fork the repository
- Create a feature branch
- Implement your changes
- Add tests for new functionality
- Run all tests to ensure nothing is broken
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue in the repository
- Check the documentation
- Contact the development team
Happy Testing! 🚀