Martin Grey
Martin Grey

Reputation: 812

Request reuse in Postman

Our team wants to automate our REST API testing. Right now, we have a collection of Postman requests and make them jump through hoops manually.

We could create a collection/folder for each testing scenario, but that would mean a ton of duplication. Our API is still under heavy development and I really don't want to fix the same thing at twenty places after it changes.

I would like to have each endpoint request only once in a collection and some kind of independent logic that can execute them in an arbitrary order. I know Postman doesn't support request reuse in any clean way, so I am looking for at least a hacky way how to do it.

Upvotes: 2

Views: 3829

Answers (1)

Martin Grey
Martin Grey

Reputation: 812

Create a file to load into the Postman Collection Runner, with the following structure:

[{
    "testSequence": ["First request name", "Second request name", "..." ],
    "anyOtherData":  "Whatever the request needs",
    "evenMoreData":  "Whatever the request needs",
    "...":           "..."
},{
    "testSequence": ["Login", "Check newsfeed", "Send a picture", "Logout" ],
    "username":  "Example",
    "password":  "correcthorsebatterystaple",
},{
    "...": "keep the structure for any other test scenario or request sequence"
}]

Put all your test sequences in that file, then make Postman check the list after each request and decide what to execute next. This can be done e. g. in a "tests block" of the whole collection:

// Use the mechanism only if there is a test scenario file
// This IF prevents the block from firing when running single requests in Postman
if (pm.iterationData.get("testSequence")) {

    // Is there another request in the scenario?
    var sequence = pm.globals.get("testSequence");
    if ((sequence instanceof Array) && (sequence.length > 0)) {

        // If so, set it as the next one
        var nextRequest = sequence.shift();
        pm.globals.set("testSequence", sequence);
        postman.setNextRequest(nextRequest);

    } else {
        // Otherwise, this was the last one. Finish the execution.
        postman.setNextRequest(null);
    }
}

If your requests need to use different data during different runs, you can define the data in the input file and use them as variables in the request.

Upvotes: 8

Related Questions