Write Parameterized API Tests With REST Assured
Test many inputs without copying tests, covering a validation matrix in a @CsvSource text block, boundary values with @ValueSource, @FieldSource and @MethodSource, a whole class per currency with @ParameterizedClass, and logging only failing exchanges.
The payment API has a rule for every field. The IBAN’s check digits must be right, the amount needs at most two decimals and can’t exceed the single-payment limit, the currency must be supported, and the execution date can’t be in the past. Fourteen rules make fourteen tests that differ in one field and one message. Copy them, and the next rule means another copy, and a fix in the shared part means fourteen fixes. In this guide, you’ll turn them into one test and a table, cover the edges with values that must pass, and repeat a whole class per currency.
Level: Advanced · Time: 30 minutes · Part of: Module 9: Data-Driven Tests and API Workflows, section 1
What You’ll Build
You’ll build two test classes. ValidationMatrixTest has four parameterized tests that run 25 times: a matrix of fourteen invalid fields, four boundary amounts, four IBANs from different countries, and three payments with several problems at once. PerCurrencyTest runs two tests once per supported currency.
Each row of the matrix is its own test, named by its inputs:
1
2
3
4
5
invalidFieldsAreRejected(String, String, String)
├─ debtorIban = 'NL00ABNA0417164300' -> must be a valid IBAN
├─ amount = '1.234' -> must have at most two decimals
├─ currency = 'JPY' -> is not supported
└─ ...
When you’re done, Maven reports 31 passing tests:
1
2
[INFO] Tests run: 31, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Write a validation matrix.
- Cover boundaries and combinations.
- Repeat a whole class per value.
What You Need
- About 30 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can build a request specification, as taught in Build Reusable Request Specifications in REST Assured, and you know what
log().ifValidationFails()does, from Log REST Assured Requests and Responses. You should have written a JUnit test with@ParameterizedTestbefore.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: this is the first section of Module 9, so you start from scratch. Create
ValidationMatrixTestin themodule-09test sources and follow every heading below. - Skip ahead: open the finished classes (
ValidationMatrixTest.javaandPerCurrencyTest.java) and read along. You can run them at any time with the command in Run the Tests.
Get the code: clone the examples repository and change into it:
1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
If you’ve already cloned it for an earlier module, run git pull instead.
Out of scope: this guide doesn’t cover tests generated at run time with @TestFactory, or multi-step workflows; they’re taught in section 2 and the sections after it.
Understand Parameterized API Tests
The problem. Validation tests for an API all look the same: build a valid request, break one field, send it, and check the status and the message. Written one by one, they bury the rules in boilerplate, and a reader can’t see at a glance which rules are covered.
The concept. A @ParameterizedTest runs one test method once for each set of arguments, and each run is its own test, named by a name pattern. JUnit has several sources for the arguments:
| Source | Arguments come from |
|---|---|
@CsvSource | Rows of separated values, here in a text block |
@ValueSource | A list of single values |
@FieldSource | A static field, such as a List |
@MethodSource | A static method that returns a Stream of Arguments |
@ParameterizedClass, available since JUnit 5.13, goes one step further: it runs every test in a class once per value, with the value injected into a field.
When to use each. Use @CsvSource when each case has several columns, such as field, value and message. Use @ValueSource or @FieldSource for single values, @MethodSource when an argument must be computed, and @ParameterizedClass when several tests share one dimension.
Write the rules as data, one row per rule, and let each row break exactly one thing.
Meet the API Under Test
Module 9 tests PaymentLifecycleApi, which covers the full life of a payment. All endpoints are under /api/v1, every request needs Authorization: Bearer test-token, and POST /payments also needs an Idempotency-Key header. A valid payment answers 201:
1
2
3
{"paymentId":"pay-8","status":"INITIATED","debtorIban":"NL91ABNA0417164300","creditorIban":"NL69INGB0123456789",
"creditorName":"Jan Jansen","amount":"120.00","currency":"EUR","reference":null,"executionDate":"2026-11-22",
"statusHistory":[{"status":"INITIATED","at":"2026-11-22T07:34:19.053803Z"}]}
Validation is real. IBANs are checked with their ISO 13616 mod-97 check digits. Amounts are decimal strings with at most two decimals, more than zero and at most 100000.00. Currencies are EUR, GBP or USD. An execution date is optional, defaults to today, and can’t be in the past. Every invalid field gives one entry in a 422:
1
2
{"type":"about:blank","title":"Unprocessable Content","status":422,"detail":"The request has invalid fields",
"instance":"/api/v1/payments","errors":[{"field":"amount","detail":"must have at most two decimals"}]}
Your tests check these values:
- The status:
201for a valid payment,422for an invalid one. errors: how many entries there are, and each entry’sfieldanddetail.currencyandamountin a created payment.
Share the Set-Up
Meet PaymentsClient
Goal: see the shared specification and payment body every test in the module uses.
The module’s support package already contains PaymentsClient:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static RequestSpecification spec(PaymentLifecycleApi api) {
return new RequestSpecBuilder()
.setBaseUri(api.baseUri())
.setPort(api.port())
.setBasePath(PaymentLifecycleApi.BASE_PATH)
.addHeader("Authorization", "Bearer " + PaymentLifecycleApi.TOKEN)
.setContentType(ContentType.JSON)
// Data-driven suites send many requests: print them only for a failing test.
.setConfig(config().logConfig(logConfig().enableLoggingOfRequestAndResponseIfValidationFails(LogDetail.ALL)))
.build();
}
/** A request with a fresh idempotency key, ready to POST a payment. */
public static RequestSpecification newPayment(PaymentLifecycleApi api) {
return given(spec(api)).header("Idempotency-Key", UUID.randomUUID().toString());
}
/** A valid payment; change entries to make it invalid. */
public static Map<String, Object> validPayment(String amount) {
Map<String, Object> payment = new LinkedHashMap<>();
payment.put("debtorIban", "NL91ABNA0417164300");
payment.put("creditorIban", "NL69INGB0123456789");
payment.put("creditorName", "Jan Jansen");
payment.put("amount", amount);
payment.put("currency", "EUR");
return payment;
}
What’s happening:
spec(..)holds everything every request needs: the address, the base path, the token and the content type.newPayment(..)adds a freshIdempotency-Key, so every row creates its own payment. Without the header, the API answers400withThe header Idempotency-Key is required.validPayment(..)returns a valid body as a mutableMap, so a test changes only the field it’s about.enableLoggingOfRequestAndResponseIfValidationFails(..)logs an exchange only when its checks fail, so 25 passing rows print nothing.
Checkpoint: open PaymentsClient.java in your IDE. It compiles as it is.
Set Up the Test Class
Goal: create the matrix class with the API.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.javanibble.module_09.section_01;
import static com.javanibble.module_09.support.PaymentsClient.newPayment;
import static com.javanibble.module_09.support.PaymentsClient.validPayment;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import com.javanibble.lifecycle.PaymentLifecycleApi;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.FieldSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
class ValidationMatrixTest {
private static PaymentLifecycleApi api;
@BeforeAll
static void startApi() {
api = PaymentLifecycleApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
}
What’s happening:
@BeforeAllstarts one API for all 25 invocations, so the matrix costs one server start, not 25.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Write a Validation Matrix
Turn Fourteen Rules Into a Table
Goal: test every field rule with one method and one row per rule.
Add this test to ValidationMatrixTest:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@ParameterizedTest(name = "{0} = ''{1}'' -> {2}")
@CsvSource(delimiter = '|', quoteCharacter = '"', textBlock = """
debtorIban | NL00ABNA0417164300 | must be a valid IBAN
debtorIban | NL91ABNA0417164301 | must be a valid IBAN
creditorIban | nl69ingb0123456789 | must be a valid IBAN
creditorIban | NL69INGB | must be a valid IBAN
creditorName | "" | must be 1 to 70 characters
amount | 0.00 | must be more than zero
amount | -5.00 | must be more than zero
amount | 1.234 | must have at most two decimals
amount | 100000.01 | exceeds the single payment limit of 100000.00
amount | ten euros | must be a decimal number as a string
currency | JPY | is not supported
currency | eur | is not supported
executionDate| 2020-01-01 | must not be in the past
executionDate| 31-12-2026 | must be a date such as 2026-12-31
""")
void invalidFieldsAreRejected(String field, String value, String expectedDetail) {
Map<String, Object> payment = validPayment("10.00");
payment.put(field, value);
newPayment(api)
.body(payment)
.when()
.post("/payments")
.then()
.statusCode(422)
.body("errors", hasSize(1)) // only the field we broke
.body("errors[0].field", equalTo(field))
.body("errors[0].detail", equalTo(expectedDetail));
}
What’s happening:
- The table reads like a specification of the rules: field, bad value, expected message. Adding a rule is adding a row.
delimiter = '|'lets values contain commas and spaces, such asten euros, and lines up the columns.quoteCharacter = '"'makes""an empty string.hasSize(1)proves the row broke only one field. Without it, a row could pass because of an error in another field.- The
namepattern gives names such asamount = '1.234' -> must have at most two decimals. Two single quotes in the pattern print one.
Checkpoint: run ValidationMatrixTest from your IDE. Fourteen tests run and pass, one per row.
Quote empty values on purpose. In
@CsvSource, an unquoted empty value arrives asnull, not"". ForcreditorName,nullgets the same message, so the row would pass while testing a missing name instead of an empty one. ForexecutionDate, which is optional,nullgives201, and the row would fail.
Cover Boundaries and Combinations
Accept the Boundary Amounts
Goal: prove the amounts at the edges of the rules are accepted.
Add this test to the class:
1
2
3
4
5
@ParameterizedTest(name = "amount {0} is accepted")
@ValueSource(strings = {"0.01", "1", "99.9", "100000.00"})
void boundaryAmountsAreAccepted(String amount) {
newPayment(api).body(validPayment(amount)).when().post("/payments").then().statusCode(201);
}
What’s happening:
0.01is the smallest amount and100000.00the largest. With0.00and100000.01in the matrix, they pin the limits down from both sides.1and99.9prove that fewer than two decimals are fine.
Checkpoint: run the class again. Eighteen tests pass.
Always add rows that must pass. A validator that rejects everything passes every negative row in the matrix; only the accepted boundaries catch it.
Reuse a List From a Field
Goal: accept IBANs from several countries, from a named list.
Add this field and test to the class:
1
2
3
4
5
6
7
8
9
10
11
static final List<String> VALID_IBANS = List.of(
"NL91ABNA0417164300", "GB33BUKB20201555555555", "DE89370400440532013000", "BE68539007547034");
@ParameterizedTest(name = "creditor IBAN {0} is accepted")
@FieldSource("VALID_IBANS")
void ibansFromSeveralCountries(String iban) {
Map<String, Object> payment = validPayment("10.00");
payment.put("creditorIban", iban);
newPayment(api).body(payment).when().post("/payments").then().statusCode(201);
}
What’s happening:
- IBANs differ in length per country, from 16 characters in Belgium to 22 in Germany and the UK, and the mod-97 check must work for all of them.
@FieldSourcekeeps the list in a named field that other tests can reuse.
Checkpoint: run the class again. Twenty-two tests pass.
Compute Arguments in a Method
Goal: prove the API reports several problems in one response, with arguments a CSV row can’t hold.
Add this method and test to the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
static Stream<Arguments> severalProblemsAtOnce() {
return Stream.of(
Arguments.of(Map.of("currency", "JPY", "amount", "0"), List.of("currency", "amount")),
Arguments.of(Map.of("debtorIban", "X", "creditorIban", "Y"), List.of("debtorIban", "creditorIban")),
Arguments.of(Map.of("executionDate", LocalDate.now().minusDays(1).toString(), "creditorName", " "),
List.of("executionDate", "creditorName")));
}
@ParameterizedTest(name = "{index}: {1} are reported together")
@MethodSource
void severalProblemsAtOnce(Map<String, Object> changes, List<String> expectedFields) {
Map<String, Object> payment = validPayment("10.00");
payment.putAll(changes);
var errors = newPayment(api).body(payment)
.when().post("/payments")
.then().statusCode(422)
.body("errors", hasSize(expectedFields.size()));
for (String field : expectedFields) {
errors.body("errors.field", hasItem(field));
}
}
What’s happening:
@MethodSourcewithout a name uses the method with the same name as the test.- The method can compute arguments, such as yesterday’s date, and pass a
Mapand aList, which a CSV row can’t. - The test proves the API reports every problem at once, so a client can fix them all in one go.
hasItem(..)doesn’t depend on the order of the errors.
Checkpoint: run the class again. All 25 tests pass.
Repeat a Whole Class per Value
Run Every Test per Currency
Goal: run several tests once per supported currency, without parameterizing each one.
Create this class next to ValidationMatrixTest:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.javanibble.module_09.section_01;
import static com.javanibble.module_09.support.PaymentsClient.newPayment;
import static com.javanibble.module_09.support.PaymentsClient.validPayment;
import static org.hamcrest.Matchers.equalTo;
import com.javanibble.lifecycle.PaymentLifecycleApi;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.Parameter;
import org.junit.jupiter.params.ParameterizedClass;
import org.junit.jupiter.params.provider.ValueSource;
@ParameterizedClass(name = "currency {0}")
@ValueSource(strings = {"EUR", "GBP", "USD"})
class PerCurrencyTest {
@Parameter
String currency;
private static PaymentLifecycleApi api;
@BeforeAll
static void startApi() {
api = PaymentLifecycleApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private Map<String, Object> payment() {
Map<String, Object> payment = validPayment("250.00");
payment.put("currency", currency);
return payment;
}
@Test
void aPaymentCanBeInitiated() {
newPayment(api).body(payment()).when().post("/payments")
.then().statusCode(201).body("currency", equalTo(currency));
}
@Test
void theAmountIsKeptExactly() {
newPayment(api).body(payment()).when().post("/payments")
.then().body("amount", equalTo("250.00"));
}
}
What’s happening:
@ParameterizedClassruns every@Testmethod once per value, and injects the value into the@Parameterfield.- Two methods and three currencies make six tests, grouped per currency in the report.
@BeforeAllstill runs once for the whole class, so all three currencies share one API.- A new currency is one more value; a new check is one more ordinary
@Testmethod.
Checkpoint: run PerCurrencyTest from your IDE. Six tests pass, under currency EUR, currency GBP and currency USD.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-09 -Dtest='ValidationMatrixTest,PerCurrencyTest'
You should see a result similar to the following, with one PerCurrencyTest block per currency:
1
2
3
4
5
6
7
8
9
[INFO] Running com.javanibble.module_09.section_01.ValidationMatrixTest
[INFO] Tests run: 25, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.611 s -- in com.javanibble.module_09.section_01.ValidationMatrixTest
[INFO] Running com.javanibble.module_09.section_01.PerCurrencyTest
[INFO] Running com.javanibble.module_09.section_01.PerCurrencyTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.013 s -- in com.javanibble.module_09.section_01.PerCurrencyTest
...
[INFO] Tests run: 31, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In the matrix, change the expected message in the -5.00 row from must be more than zero to must be positive, and run the command again. Above the result, REST Assured logs the one exchange that failed: a POST with "amount": "-5.00", and a 422 with "detail": "must be more than zero". Then Maven reports:
1
2
3
4
5
6
7
[ERROR] com.javanibble.module_09.section_01.ValidationMatrixTest.invalidFieldsAreRejected(String, String, String)[7] -- Time elapsed: 0.011 s <<< FAILURE!
...
[ERROR] Failures:
[ERROR] ValidationMatrixTest.invalidFieldsAreRejected:74 1 expectation failed.
JSON path errors[0].detail doesn't match.
Expected: must be positive
Actual: must be more than zero
Only the failing row’s request and response are printed; the other 24 stay quiet. Maven’s console names the row by its index, [7], not by the name pattern. Your IDE shows amount = '-5.00' -> must be positive, and the logged body tells you which row it was.
Put the message back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
A row fails with errors of size 2 | The base payment or the row breaks a second field | Check validPayment(..), and change one field per row |
| A row with an empty value gets the wrong result | An unquoted empty value arrives as null | Quote it as "" for an empty string |
Maven’s report shows [7] instead of the row’s name | Surefire’s default reports use the invocation index | Read failures in the IDE, or configure Surefire’s reporter to use display names |
| The console is full of request logs | Logging is unconditional | Use enableLoggingOfRequestAndResponseIfValidationFails(..) in the specification |
400 with The header Idempotency-Key is required | The request started from spec(..), not newPayment(..) | Use newPayment(api) for POST /payments |
Try It Yourself
Exercise 1: Pin Down the Creditor Name Length
Add a test called creditorNameLengths. Use @MethodSource to pass a name length and an expected status: 1 and 201, 70 and 201, 71 and 422. Build the name with "A".repeat(length), and name each invocation a creditor name of {0} characters gives {1}.
Hint
A 71-character name is long to write in a CSV row, which is why a method fits better. Pass Arguments.of(1, 201) and so on, and take int length, int expectedStatus as parameters.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
static Stream<Arguments> creditorNameLengths() {
return Stream.of(Arguments.of(1, 201), Arguments.of(70, 201), Arguments.of(71, 422));
}
@ParameterizedTest(name = "a creditor name of {0} characters gives {1}")
@MethodSource
void creditorNameLengths(int length, int expectedStatus) {
Map<String, Object> payment = validPayment("10.00");
payment.put("creditorName", "A".repeat(length));
newPayment(api).body(payment).when().post("/payments").then().statusCode(expectedStatus);
}
Exercise 2: Check the Limit in Every Currency
Add a test to PerCurrencyTest called anAmountAboveTheLimitIsRejected. Post 100000.01 in the class’s currency, and check that the API answers 422 with the detail exceeds the single payment limit of 100000.00.
Hint
Start from validPayment("100000.01") and put the currency field, as payment() does. The new method runs three times, once per currency, without any extra annotation.
Solution
1
2
3
4
5
6
7
8
@Test
void anAmountAboveTheLimitIsRejected() {
Map<String, Object> payment = validPayment("100000.01");
payment.put("currency", currency);
newPayment(api).body(payment).when().post("/payments")
.then().statusCode(422).body("errors[0].detail", equalTo("exceeds the single payment limit of 100000.00"));
}
Summary
You built ValidationMatrixTest, which covers fourteen field rules as a table, four boundary amounts, four countries’ IBANs and three combined problems, and PerCurrencyTest, which runs two tests per supported currency. The API’s rules now read as data, and a new rule is one more row.
- A
@ParameterizedTestruns one method per set of arguments, each a separate test named by itsnamepattern. @CsvSourcewith a text block anddelimiter = '|'makes validation rules readable; quote empty values, because unquoted ones arenull.@ValueSourcecovers boundaries,@FieldSourcereuses a named list, and@MethodSourcecomputes arguments.@ParameterizedClassruns a whole class per value, with the value in a@Parameterfield.- Check that each row breaks one thing only, add rows that must pass, and log only the exchanges that fail.
Here are the commands you used in this guide:
1
2
git clone https://github.com/javanibble/rest-assured-examples.git
mvn test -pl module-09 -Dtest='ValidationMatrixTest,PerCurrencyTest'
What’s Next
Next: continue with Generate Dynamic API Tests With REST Assured, which generates tests at run time with @TestFactory, so every endpoint in a list gets the same security checks.
The code:
- The finished test classes:
ValidationMatrixTest.javaandPerCurrencyTest.java - The shared set-up:
PaymentsClient.java - The code and run commands for this module: Module 9 README
Go deeper:
- JUnit User Guide: Parameterized Tests, for every argument source and
@ParameterizedClass. - Maven Surefire: Using JUnit Platform, for reporting display names instead of indexes.
- International Bank Account Number, for the IBAN format and the mod-97 check.
Related guides:
- Build Reusable Request Specifications in REST Assured, for the specification
PaymentsClientbuilds. - Log REST Assured Requests and Responses, for logging only when validation fails.
