Based off of @lucas-nguyen-17 answer I did the same thing but made an array of tests and only used one request by using pm.variables
instead of pm.environment
so the variables are only local to the test and not the whole environment.
Pre-request Script
let allTests = [
{ name: '1', statusCode: 200, data: {id: 1, title: 'title1'} },
{ name: '2', statusCode: 200, data: {id: 2, title: 'title2'} },
{ name: '3', statusCode: 200, data: {id: 3, title: 'title3'} },
{ name: "null id", statusCode: 400, data: {id: null} },
{ name: "happy", statusCode: 200, data: {} },
];
// Set test data on only first iteration in runner
if (pm.variables.get('testData') === undefined {
pm.variables.set('testData', JSON.stringify(allTests));
}
// Get the current test and remove it from the test still needing to run
let testData = JSON.parse(pm.variables.get('testData'));
let currentTestData = testData.shift()
pm.variables.set('testData', JSON.stringify(testData))
pm.variables.set('currentTestData', JSON.stringify(currentTestData))
// Combine current test data with a happy object so all parts aren't needed on every test
let happy = {id: '0', title: 'title'};
let test = {
...happy,
//overwrite happy with variables in test data
...currentTestData.data
};
// Set the variables for the test
pm.variables.set('id', test.id);
pm.variables.set('title', test.title);
Tests
let test = JSON.parse(pm.variables.get('currentTestData'));
pm.test(`Test(${test.name}) Status code is ${test.statusCode}`, function () {
pm.response.to.have.status(test.statusCode);
});
// Run the next test if any are left
let testData = JSON.parse(pm.variables.get('testData'));
if (testData.length > 0){
postman.setNextRequest(pm.info.requestName);
}
When not using the runner this will always just run the first test case but using the runner runs them all.