PostMock is a powerful mocking framework that uses Postman.
It brings Postman into your application and provides the following capabilities:
- Mock any request with responses from Postman.
- View network calls linked to postman requests.
Find our public api collection in Postman called PostMock. Which we used in demo app inside.
import PostMockSDK
struct ContentView: View {
var body: some View {
DogsList()
// Add PostMock button or use PostMockView direclty and add it to any view you wan't, or call it on shake.
.overlayPostMockButton()
.onAppear {
// Provide your POSTMAN_API_KEY and WORKSPACE_ID wich api collections you want to use
let config = PostMock.Config(apiKey: "<POSTMAN_API_KEY>",
workspaceID: "<WORKSPACE_ID>")
PostMock.shared.configurate(with: config)
/// Add some environment variables (optional), see description below
PostMock.shared.environment.set(key: "host",
scope: .request,
provider: { "https://dogapi.dog" })
}
}
}
You also need MockServer in Postman for api collection.
To match requests from the app to Postman requests, we can use templates or set a specific header x-postmock-request-id
to the request.
You can provide some variables to make the mock more specific.
Some of these variables are global and are applied to any request containing the placeholder.
We set them up in the code:
PostMock.shared.environment.set(key: "host",
scope: .request,
provider: { "https://dogapi.dog" })
If you do not specify global variables like {{host}}
, they will be matched to any string.
It’s not a problem when you have only one host for requests.
You can mock some request in preview or tests. There is opportunity to set mock from code:
/// response id from postman
let mastiff200 = "1122734-8c545657-d643-4db4-b216-d16d699b27fa"
/// Default MockServer from workspace https://www.postman.com/universal-moon-430028/workspace/postmock
PostMock.shared.mockServer = MockServer(host: "0997c312-c8ea-435a-8ffd-4a98f4214024.mock.pstmn.io")
Mock
.request("GET", url: "{{host}}/api/v2/facts")
.with(responseID: .mastiff200)
.set()
PostMock.shared.mockIsEnabled = true