Answer
Scenario: Testing API Authentication
You are tasked with testing the authentication functionality of an API using Rest Assured.
Approach
Step 1: Understand the Auth Mechanism
First, I would ensure that I have clear documentation or understanding of the authentication mechanism — whether it is basic authentication, OAuth, or token-based authentication.
Step 2: Write Test Cases
Happy Path — Valid Credentials:
@Test
public void testLoginWithValidCredentials() {
String body = "{ \"username\": \"admin\", \"password\": \"admin123\" }";
Response response = given()
.contentType(ContentType.JSON)
.body(body)
.when()
.post("/api/auth/login");
assertEquals(response.getStatusCode(), 200);
assertNotNull(response.jsonPath().getString("token"));
// Save token for subsequent requests
String token = response.jsonPath().getString("token");
System.out.println("Token: " + token);
}
Negative Path — Invalid Credentials:
@Test
public void testLoginWithInvalidCredentials() {
String body = "{ \"username\": \"admin\", \"password\": \"wrongpassword\" }";
given()
.contentType(ContentType.JSON)
.body(body)
.when()
.post("/api/auth/login")
.then()
.statusCode(401)
.body("error", equalTo("Invalid credentials"));
}
Missing Token Scenario:
@Test
public void testAccessProtectedRouteWithoutToken() {
given()
.when()
.get("/api/protected/resource")
.then()
.statusCode(401)
.body("message", containsString("token"));
}
Expired Token Scenario:
@Test
public void testWithExpiredToken() {
String expiredToken = "eyJhbGciOiJIUzI1NiJ9.expired.signature";
given()
.header("Authorization", "Bearer " + expiredToken)
.when()
.get("/api/users")
.then()
.statusCode(401)
.body("error", equalTo("Token expired"));
}
Step 3: Verify Edge Cases
- ✓Empty username/password → 400 Bad Request
- ✓SQL injection in credentials → 400/401 (not 500)
- ✓Very long password strings → 400
- ✓Special characters in password → Should work if valid
Test Coverage Matrix
| Scenario | Expected Status |
|---|---|
| Valid credentials | 200 |
| Wrong password | 401 |
| Non-existent user | 401 or 404 |
| Missing auth header | 401 |
| Expired token | 401 |
| Malformed token | 401 |
| Missing required field | 400 |
