Safely Refactoring Endpoints with Postman Tests
Refactoring endpoints is a common task in development, but it always requires caution to ensure the expected behavior remains unchanged. With Postman, you can validate changes by comparing responses before and after the refactoring.
Step 1: Creating a New Environment
Create a new environment in Postman and set it as active. This will store all your variables for use in requests and tests.
Step 2: Setting Up the Main Collection
Create a collection to store the requests before the code changes. Name it "main".
For each request, add a post-response script in the "Scripts" tab to save the response payload to a variable. Use the code below, adjusting the variable name for each request:
pm.environment.set("variableName", JSON.stringify(pm.response.json()));Note: Replace variableName with a unique identifier for each request.
Create a second collection, named "staging", to store the requests after the code changes.
Duplicate the requests from the "main" collection into this new collection.
In the "Scripts" tab of each request, add the following post-response script to compare the current response payload with the corresponding variable from the "main" collection:
pm.test("Responses are equivalent", function () { const mainResponse = JSON.parse(pm.environment.get("variableName"));
const stagingResponse = pm.response.json();
pm.expect(stagingResponse).to.eql(mainResponse);
});
Note: Ensure that the variable name in get("variableName") matches the one defined in the "main" collection script.
Step 4: Save Main Variables
Run the project without applying any changes.
Execute the requests in the "main" collection to save the payloads into variables.
Step 5: Compare the Payloads
Apply the necessary changes to the endpoints and restart the project.
Execute the requests in the "staging" collection to validate the responses.


Comentários
Postar um comentário