mock server postman что такое
Simulate a back end with Postman’s mock service
Throughout the development process, delays on the front end or back end can hold up dependent teams from completing their work efficiently. Some API engineers already use Postman to work on endpoints without relying on a front-end UI to simulate API requests.
Now, Postman has developed a new mock service to enable teams to simulate a backend server. Front-end developers can simulate each endpoint in a Postman Collection (and corresponding environment) to view the potential responses, without actually spinning up a back end.
Front-end, back-end and API teams can now work in parallel, freeing up developers who were previously delayed as a result of these dependencies. Let’s walk through this step by step.
Set up a Collection for mocking
Navigate to every request in the Collection testAPI that you would like to include in this simulation, and save responses with details about the response body, header or status codes that you would like to see returned by that endpoint. In this example, we will save 2 responses with status codes of 200 and 401 for this particular request. Once you save the desired responses, the Collection is ready for mocking.
Retrieve information needed for mock creation
Let’s retrieve the collectionId of testAPI using the Postman Pro API. Get a list of all your Collections using the GET All Collections endpoint. Search for the name of your Collection and retrieve the uid from the results, which will be used as the collectionId in the next step.
As an optional step, you can include an environment template as a part of your simulation by retrieving the environmentId of testAPIEnv using the Postman Pro API. Get a list of all your environments using the GET All Environments endpoint. Search for the name of your environment and retrieve the uid from the results, which will be used as the environmentId in the next step.
Create a mock using the Postman Pro API
Create a mock using the POST Create Mock endpoint with the collectionId and environmentId you retrieved previously.
Verify that the mock has been created using the GET All Mocks endpoint, and your Collection is now ready to be simulated.
Run the mock service
Mock your Collection using the following url: https://<
Add the request header(s):
And there we have it. We have walked through the entire process of mocking a Collection from start to finish. We hope that you find this feature useful in increasing the efficiency of your team collaboration. And as always please reach out to us if you have any comments or questions.
Update: Now you can set up a mock server from the Postman app with examples.
Mocking with examples
Mock servers simulate an API by returning predefined data, enabling you to develop or test against an API before it’s production-ready (or without using production data). In Postman, mock servers rely on examples saved in a collection to return mock data. Follow the steps below to get a hands-on demonstration of how mock servers and examples work together, and to learn how you can integrate them into your API workflow.
Creating a mock server
The steps below walk you through the process of creating a mock server in Postman. First, you’ll set up some basics that are required for mock servers to work. Once your mock server is up and running, you’ll send requests to it and see how your examples are used to return data.
This request calls the Postman Echo service which you can use to test REST or SOAP clients and make sample API calls. The resulting response displays in the response pane below the request.
Select Save to save the request in a collection. Collections are groups of requests that you can use to organize your work and create API workflows.
Select New Collection at the bottom of the Save Request dialog box. Enter C1 for the collection name and select Create. Then select Save to save the request to the new collection.
To save the response you received from the Postman Echo service, select Save Response > Save as example. The example is saved underneath the request, inside the C1 collection.
Select Collections in the left sidebar, expand the C1 collection and the request, and then select the example to open it.
When you’re done configuring the mock server, select Create Mock Server. You can access the mock server at any time by selecting Mock Servers in the left sidebar.
First, copy the mock server URL. Select Mock Servers in the left sidebar, select the M1 mock server, and then select Copy Mock URL.
Next, create a new request by selecting + or by selecting New > HTTP Request. Paste the mock URL into the new request and select Send.
Sending a GET request to https://postman-echo.com/test returns a 404 error, which you saved as another example. The collection C1 now has two requests and two saved examples:
Finally, repeat step 5 above, but this time add the path /test to the end of the mock server URL when sending the request. This returns the expected 404 response.
Generating random data with dynamic variables
As you’ve seen in this demonstration, you define the data to be returned by the mock server in your examples. However, there may be cases when you want the mock server to return a response containing random data.
To have your mock server return random data, use dynamic variables in your example’s response body. Dynamic variables are resolved as part of the mock server response and replaced with random data. Dynamic variables are useful for generating random data when mocking an API, and you can use them for exploratory testing and writing rich, data-driven tests.
For instance, your example’s response body might contain dynamic variables as follows:
When you call the mock server endpoint, you’ll see the response data change to something like:
See Dynamic Variables for a full list of dynamic variables for generating random data.
Using query parameters
Postman’s mock service uses a matching algorithm to select the most appropriate saved example to return in response to a request. As part of this algorithm, the mock server looks at the query parameters when matching requests to saved examples. If you have examples that differ only in their query parameters, you can mock different responses for different query parameters on the same request path. In this case, the mock server will return the exact response matching that request path and the corresponding query parameters.
Here’s a scenario that illustrates how matching query parameters works:
In Example1, the parameter id has a value of 1 :
In Example2, the parameter id has a value of 5 :
In this scenario, Example1 and Example2 are passing 1 and 5 respectively. When you send a request to the mock server URL and pass these different query parameters, Postman returns the exact response that matches both the path and the passed parameters.
If no exact match is found, Postman returns the best response based on its matching algorithm.
Mocking GraphQL queries
Postman’s mock service enables you to mock GraphQL queries. To mock GraphQL queries, make a request to the mock server using the request path and request body saved in the examples in the mocked collection.
Make sure to set the Content-type header to application/json in your examples.
Also make sure to pass the x-mock-match-request-body header with a value of true when sending a request to the mock server URL.
Postman Mock Server
Mock Server in POSTMAN
A Mock Server is a virtual server that can be your own computer or any software which can be used to act like a real server. A Mock server is used during different API testing when various responses have to be received which are not readily available on the web servers or for some testing that cannot be performed on real servers for security issues.
POSTMAN provides a great facility letting you create a Mock Server inside it.
Creating the MOCK Server in POSTMAN
For creating Mock Server in POSTMAN, you don’t really need any external extensions or applications, but the Mock server is inbuilt in POSTMAN. Let us see how to use it.
Go to the New button in POSTMAN and you will see the option for Mock Server.
Select the Mock Server.
As can you see in the above image, the first column is for the method type. (We selected GET ). In the next column, the Request Path has to be inserted. (<
We can write the response text as plain or HTML document, JSON document, etc.
Now hit the Next button.
Then click into the Create Mock Server, and your Mock server is created.
Now, on the left side of the POSTMAN interface, your Mock Collection should be displayed along with all other existing collections.
As shown in the above request, you can see that a request has been automatically created by POSTMAN for making requests into the Mock server.
Now, open the request and click the send button to send the request.
Now, go the Response Section, and you must be able to see the custom response that you created at the time of creating the Mock Server.
Creating a JSON Response in the Mock Server
So far we have only seen how to create a response in the Mock server and how a request can be made to get the response. Now, we shall see how to create a JSON response and how a request can be made to get the response from the Mock Server.
Let us create a JSON response into the Mock Server. To edit the response, just open the request and then go to the Example in the top right corner of the POSTMAN page.
As you click Examples, you will get a drop-down option called Default. Click into that option and you will be able to edit your response.
As you click into Default option, you will get an area to edit your response. Click into the drop-down menu right to the Preview section in the body section and then select JSON(you can select anyone, but now we are concerned about creating JSON response, so we shall choose JSON response).
After selecting the JSON file, in the body section, write your JSON Response.
Now, hit the save example button and then click to return back.
In the image, the left side button demo, you can return back to the request.
Now, send the request. And wait for some time. Even though the response is made from your local machine through POSTMAN itself, it will take some time to process the request and the response.
Response from Mock Server :
Performing Assertion into Mock Server’s Response
As we saw earlier, in the Assertion Chapter, that assertions are nothing but writing test code. The POSTMAN inbuilt code snippets can be used the javascript code can be customized for making different assertions on the Mock Server’s Response.
Performing Assertions on the Mock Server’s Response is similar to the assertions we make on the Response that we obtain from a distant or remote server(what we call a real server).
Checking the HTTP status code
Go to the Test Tab of the Request and edit the code below:
Click the send button to send the request again and after the response is received, to the Result tab in the Response section and see the result.
Accessing data from the JSON Response
Any data values from the JSON Response can be obtained by accessing the JSON path for that variable. For example, consider the response below.
Edit the following code into the Test tab editor:
Now, click the send button to send the request and after the response is received, see the Result.
Now, send the request and see the Result:
Advanced assertions on the response of a Mock server
Advanced assertions can also be performed on the response from the Mock server. We have already see what are the different types of programming concepts that can be applied to creating assertions. Some of them were conditional statements, some were loops and switch statements.
Assertion using Conditional Statement:
Generally, the conditional statement is a if. When a condition is satisfied or is found to be true, then the if statement gets executed. In this example, we shall that how can we check the existence of a name inside the response. This can be checked by comparing the JSON path of the data with the value we want to check.
In the above example, the line if(mydata == «Rahul») checks the condition for the presence of the name Rahul in the given path.
Console Output :
Checking for data in two different path
It may be possible, that a data value if not found in one path, then can be found in a different path of the JSON response. To check a value in two different places, either we can use two of the statements or can use an OR operator inside the if statement.
Let us check for the name Rahul in one path and the id =1 in a different path. If anyone (name or the id) is matched, then At least one condition is satisfied will be printed in the console, otherwise, None of the condition is satisfied will be printed in the console.
Now, edit the following code into the Tests Tab of the request:
Now, send the request and after the response is received, see the console output:
Using code snippets on Mock server response
As discussed earlier, code snippets are nothing but ready-made codes that are integrated into POSTMAN to create assertions, check status code, search for a keyword, setting or getting variables.
Code snippets help in creating scripts easily and also the time to write code for a simple test can be reduced significantly. Let us see the applications of some code snippets.
To go to POSTMAN snippets, go to the right side of the interface and select the code snippet you want and it will be automatically pasted into the editor.
Some of the snippets which are used in Pre-Test scripts are setting variables, getting variables, etc. On the other hand, some of the snippets which are used in the Tests(which gets executed after the response are received) are: checking status code, performing assertions, implementing other filters, etc.
Checking the status code:
To check the status code, Select Tests Tab of the request, and once the editor is opened, the snippets must be visible to you.
Now, send the request and wait for the response. Once the response is received, go to the Result tab of the Response and see the result:
Searching for a string in the body
Now, send the request and check the result after the response is received.
Matching Status Code
When a response is received, there can be different status codes associated with the response. For example, when a response is received from the server without any interruption or without any error, the status code turns out to be 200.(which means OK).
Now, it is also possible that the server returns some different codes like 201, 202, etc, which are somewhat similar to the Ok status code: 200. Now, let us see how we can check for different status code:
In this example, I shall check for the status code: 200, 201, 202.
Edit the following code into the Tests tab of the request :
In the above code, we have checked for the code- 201, 202, and 200 using the statement:
Now, send the request and see the result tab after the response is received from the server:
As you can see in the above response, it’s showing PASS.
Check for the Response Time
Response time is the time taken by the server to send the response. All the time the server will not be able to send the response with similar efficiency or speed. And the response time decides how good the website is.
Use the code snippets to see the response time or edit the code below:
As shown in the above code, we are checking for the response time to be less than 200 mili-seconds. After it is done, send the request and wait for the response. If the response from the server, has any of the three status codes, the test will PASS.
Mocking by API
You can mock a collection directly from Postman. Additionally, you can create a mock using the Postman API. Let’s walk through this step by step.
Set up a collection for mocking
Navigate to every request in the Collection testAPI that you would like to include in this simulation, and save responses with details about the response body, header or status codes that you would like to see returned by that endpoint. This example saves two responses with status codes of 200 and 401 for this particular request. Once you save the desired responses, the Collection is ready for mocking.
Note: In addition to mocking a collection with a saved response, you can also mock a request and response using examples.
Retrieve information needed for mock creation
Let’s retrieve the collectionId of testAPI using the Postman API. Get a list of all your Collections using the GET All Collections endpoint. Search for the name of your Collection and retrieve the uid from the results, which will be used as the collectionId in the next step.
As an optional step, you can include an environment as a part of your simulation by retrieving the environmentId of testAPIEnv using the Postman API. Get a list of all your environments using the GET All Environments endpoint. Search for the name of your environment and retrieve the uid from the results, which will be used as the environmentId in the next step.
Create a mock using the Postman API
Create a mock using the POST Create Mock endpoint with the collectionId and environmentId you retrieved previously.
Verify that the mock has been created using the GET All Mocks endpoint, and your Collection is now ready to be simulated.
Run the mock service
Mock your Collection using the following url:
Add the request headers:
Mock requests and responses with examples
In the previous example, a saved response was used to mock a collection. You can also mock a request and response using examples in Postman before sending the actual request or setting up a single endpoint to return the response. With examples, you can mock raw responses and save them. Then, you’ll be able to generate a mock endpoint for each of them using Postman’s mock service.
Введение в Postman
“Разработка API сложна, Postman делает её лёгкой” © Postdot Technologies, Inc
Когда видишь описание инструментов Postman — захватывает дух, просыпается чувство всевластия над своим будущим детищем. Кажется, что и взрощенные в прошлом «монстры» наконец-то падут перед тобой!
В этой статье мы расскажем о Postman и попробуем написать свой первый скрипт.
Postman
Основное предназначение приложения — создание коллекций с запросами к вашему API. Любой разработчик или тестировщик, открыв коллекцию, сможет с лёгкостью разобраться в работе вашего сервиса. Ко всему прочему, Postman позволяет проектировать дизайн API и создавать на его основе Mock-сервер. Вашим разработчикам больше нет необходимости тратить время на создание «заглушек». Реализацию сервера и клиента можно запустить одновременно. Тестировщики могут писать тесты и производить автоматизированное тестирование прямо из Postman. А инструменты для автоматического документирования по описаниям из ваших коллекций сэкономят время на ещё одну «полезную фичу». Есть кое-что и для администраторов — авторы предусмотрели возможность создания коллекций для мониторинга сервисов.
Введение
1 — коллекция, 2 — папка, 3 — запрос
Главные понятия, которыми оперирует Postman это Collection (коллекция) на верхнем уровне, и Request (запрос) на нижнем. Вся работа начинается с коллекции и сводится к описанию вашего API с помощью запросов. Давайте рассмотрим подробнее всё по порядку.
Collection
Коллекция — отправная точка для нового API. Можно рассматривать коллекцию, как файл проекта. Коллекция объединяет в себе все связанные запросы. Обычно API описывается в одной коллекции, но если вы желаете, то нет никаких ограничений сделать по-другому. Коллекция может иметь свои скрипты и переменные, которые мы рассмотрим позже.
Folder
Папка — используется для объединения запросов в одну группу внутри коллекции. К примеру, вы можете создать папку для первой версии своего API — «v1», а внутри сгруппировать запросы по смыслу выполняемых действий — «Order & Checkout», «User profile» и т. п. Всё ограничивается лишь вашей фантазией и потребностями. Папка, как и коллекция может иметь свои скрипты, но не переменные.
Request
Запрос — основная составляющая коллекции, то ради чего все и затевалось. Запрос создается в конструкторе. Конструктор запросов это главное пространство, с которым вам придётся работать. Postman умеет выполнять запросы с помощью всех стандартных HTTP методов, все параметры запроса под вашим контролем. Вы с лёгкостью можете поменять или добавить необходимые вам заголовки, cookie, и тело запроса. У запроса есть свои скрипты. Обратите внимание на вкладки «Pre-request Script» и «Tests» среди параметров запроса. Они позволяют добавить скрипты перед выполнением запроса и после. Именно эти две возможности делают Postman мощным инструментом помогающим при разработке и тестировании.
1 — вкладки с запросами, 2 — URL и метод, 3 — параметры запроса, 4 — параметры ответа
Скрипты
«Postman Sandbox» это среда исполнения JavaScript доступная при написании «Pre-request Script» и «Tests» скриптов. «Pre-request Script» используется для проведения необходимых операций перед запросом, например, можно сделать запрос к другой системе и использовать результат его выполнения в основном запросе. «Tests» используется для написания тестов, проверки результатов, и при необходимости их сохранения в переменные.
Последовательность выполнения запроса (из оф. документации)
Помимо скриптов на уровне запроса, мы можем создавать скрипты на уровне папки, и, даже, на уровне коллекции. Они называются также — «Pre-request Script» и «Tests», но их отличие в том, что они будут выполняться перед каждым и после каждого запроса в папке, или, как вы могли догадаться, во всей коллекции.
Последовательность выполнения запроса со скриптами папок и коллекций (из оф. документации)
Переменные
Postman имеет несколько пространств и областей видимости для переменных:
Глобальные переменные и переменные окружения можно создать, если нажать на шестеренку в правом верхнем углу программы. Они существуют отдельно от коллекций. Переменные уровня коллекции создаются непосредственно при редактировании параметров коллекции, а локальные переменные из выполняемых скриптов. Также существуют переменные уровня данных, но они доступны только из Runner, о котором мы поговорим позже.
Приоритет пространств переменных (из оф. документации)
Особенностью переменных в Postman является то, что вы можете вставлять их в конструкторе запроса, в URL, в POST параметры, в Cookie, всюду, используя фигурные скобки в качестве плейсхолдера для подстановки.
<
Из скриптов переменные тоже доступны, но получить их поможет вызов стандартного метода встроенной библиотеки pm:
Collection Runner
Предназначен для тестирования и выполнения всех запросов из коллекции или папки, на ваш выбор. При запуске можно указать количество итераций, сколько раз будет запущена папка или коллекция, окружение, а также дополнительный файл с переменными. Стоит упомянуть, что запросы выполняются последовательно, согласно расположению в коллекции и папках. Порядок выполнения можно изменить используя встроенную команду:
После выполнения всех запросов формируется отчет, который покажет количество успешных и провальных проверок из скриптов «Tests».
Collection Runner
Console
Пользуйтесь консолью для отладки ваших скриптов, и просмотра дополнительной информации по запросам. Консоль работает, как во время запуска одного запроса, так и во время запуска пакета запросов через Runner. Чтобы её открыть, найдите иконку консоли в нижнем левом углу основного экрана приложения:
Практика
Так как создание коллекций и запросов в конструкторе не должно вызвать затруднений, практическую часть посвятим написанию скриптов, и рассмотрим как создать цепочку запросов с тестами. Перед началом создайте новую коллекцию, назовите её “Habra”, затем создайте новое окружение под названием «Habra.Env»
Шаг 1
Создайте новый запрос, в качестве URL укажите https://postman-echo.com/get?userId=777, а метод оставьте GET. Здесь и далее для простоты и удобства мы будем использовать echo-сервер любезно предоставленный разработчиками Postman. Сохраните запрос в коллекцию «Habra» и назовите “Get user id”, он будет имитировать получение идентификатора пользователя от сервера. Перейдите на вкладку «Tests» и напишите следующий код:
С помощью этого скрипта мы проверили статус и формат ответа, а также сохранили полученный из ответа идентификатор пользователя в переменную окружения для последующего использования в других запросах. Чтобы проверить работу нашего теста, запустите запрос. В панели информации об ответе, во вкладке «Tests» вы должны увидеть зелёный лейбл “PASS”, а рядом надпись “Status is ok, response is json”.
Шаг 2
Теперь давайте попробуем вставить идентификатор нашего пользователя в json запрос. Создайте новый запрос, в качестве URL укажите https://postman-echo.com/post, выберите метод POST, установите тип для тела запроса raw — application/json, а в само тело вставьте:
Сохраните запрос в нашу коллекцию, и назовите «Update username», он будет запрашивать импровизированную конечную точку для обновления username пользователя. Теперь при вызове запроса вместо <
В нашем новом тесте мы сравниваем полученный от сервера userId с тем, что хранится у нас в переменной окружения, они должны совпадать. Запустите запрос и убедитесь, что тесты прошли. Хорошо, двигаемся дальше.
Шаг 3
Вы могли заметить, что два тестовых скрипта имеют одинаковую проверку формата и статуса:
Пока мы не зашли слишком далеко, давайте исправим эту ситуацию и перенесем эти тесты на уровень коллекции. Откройте редактирование нашей коллекции, и перенесите проверку формата и статуса во вкладку «Tests», а из запросов их можно удалить. Теперь эти проверки будут автоматически вызываться перед скриптами «Tests» для каждого запроса в коллекции. Таким образом мы избавились от копирования данной проверки в каждый запрос.
Шаг 4
Мы научились записывать и получать переменные окружения, настало время перейти к чему-то потяжелее. Давайте воспользуемся встроенной библиотекой tv4 (TinyValidator) и попробуем проверить правильность схемы json объекта. Создайте новый запрос, в качестве URL используйте https://postman-echo.com/post, установите метод в значение POST, для тела запроса укажите raw — application/json, и вставьте в него:
После запуска запроса echo-сервер должен вернуть нам нашу json модель в качестве ответа в поле «data», таким образом мы имитируем работу реального сервера, который мог бы прислать нам информацию о профиле Боба. Модель готова, напишем тест, проверяющий правильность схемы:
Готово, мы провалидировали схему объекта profile. Запустите запрос и убедитесь, что тесты проходят.
Шаг 5
У нас получился небольшой путь из 3-х запросов и нескольких тестов. Настало время полностью его протестировать. Но перед этим, давайте внесем небольшую модификацию в наш первый запрос: замените значение “777” в URL на плейсхолдер “<
Теперь запустим Runner. В качестве «Collection Folder» выберем «Habra». В качестве «Environment» поставим «Habra.Env». Количество итераций оставляем 0, а в поле «Data» выбираем наш файл users.json. По этому файлу «Collection Runner» поймет, что ему нужно совершить 4 итерации, и в каждой итерации он заменит значение переменной «newUserId» значением из массива в файле. Если указать количество итераций больше, чем количество элементов в массиве, то все последующие итерации будут происходить с последним значением из массива данных. В нашем случае после 4 итерации значение «newUserId» всегда будет равно 50000. Наш “Data” файл поможет пройти весь наш путь с разными newUserId, и убедиться, что независимо от пользователя все выполняется стабильно.
Запускаем наши тесты нажатием «Run Habra». Поздравляем вы успешно создали коллекцию и протестировали наш импровизированный путь с помощью автотестов!
Тестирование коллекции «Habra»
Теперь вы знаете, как создавать скрипты и вполне можете написать парочку тестов для своего проекта.
Отдельно хочу отметить, что в реальном проекте мы не держим все запросы в корне коллекции, а стараемся раскладывать их по папкам. Например, в папке «Requests» мы складываем все возможные запросы описывающие наш API, а тесты храним в отдельной папке «Tests». И когда нам нужно протестировать проект, в «Runner» запускаем только папочку «Tests».
Полезно знать
В завершении приведем основные команды, которые вам могут понадобиться во время написания скриптов. Для лучшего усвоения, попробуйте поиграться с ними самостоятельно.
Установка и получение переменных
Тестирование или asserts
Создание запросов
Получение ответа для основного запроса
Ответ доступен только во вкладке “Tests”
Работа со встроенными библиотеками
Документация регламентирует наличие некоторого количества встроенных библиотек, среди которых — tv4 для валидации json, xml2js конвертер xml в json, crypto-js для работы с шифрованием, atob, btoa и др.
Некоторые из библиотек, например, как tv4 не требуют прямого подключения через require и доступны по имени сразу.
Получение информации о текущем скрипте
Управление последовательностью запросов из скрипта
Стоит отметить, что данный метод работает только в режиме запуска всех скриптов.
После перехода на следующий запрос Postman возвращается к линейному последовательному выполнению запросов.
Создание глобального хелпера
В некоторых случаях вам захочется создать функции, которые должны быть доступны во всех запросах. Для этого в первом запросе в секции “Pre-request Script” напишите следующий код:
А в последующих скриптах пользуемся им так:
Это лишь небольшой список полезных команд. Возможности скриптов гораздо шире, чем можно осветить в одной статье. В Postman есть хорошие «Templates», которые можно найти при создании новой коллекции. Не стесняйтесь подглядывать и изучать их реализацию. А официальная документация содержит ответы на большинство вопросов.
Заключение
Основные плюсы, которые подтолкнули нас к использованию Postman в своём проекте:
Среди минусов можно выделить:
У каждого проекта свои подходы и взгляды на тестирование и разработку. Мы увидели для себя больше плюсов, чем минусов, и поэтому решили использовать этот мощный инструмент, как для тестирования, так и для описания запросов к API нашего проекта. И по своему опыту можем сказать, даже, если вы не будете использовать средства тестирования, которые предоставляет Postman, то иметь описание запросов в виде коллекции будет весьма полезно. Коллекции Postman это живая, интерактивная документация к вашему API, которая сэкономит множество времени, и в разы ускорит разработку, отладку и тестирование!
P.S.:
Основной функционал Postman бесплатен и удовлетворяет ежедневным нуждам, но есть некоторые инструменты с рядом ограничений в бесплатной версии: