cihangirs
cihangirs

Reputation: 55

How to stub network requests on UITesting

Is there any way to stub network requests for UITests which are written in Swift?

I’ve already installed OHHTTPStubs pods but couldn’t managed to stub my network requests via using its methods which is because UITest target and application target are executed in different threads.

I’ll appreciate any recommendations.

Upvotes: 1

Views: 2474

Answers (2)

HHK
HHK

Reputation: 1412

You have two different options here:

  1. You can take Oletha's approach, and touch the networking in your app's code. You'll have to stub the NSURLSession to inject the response you want, and use some launch arguments to identify when to use the stubbed session instead of the regular one. More details in this article on how to do so: http://masilotti.com/ui-testing-stub-network-data/

  2. You can run a local server and inject your data directly from your test code. The huge advantage is that you don't have to touch your app code at all. You can also easily change your response during your test, which is not possible with the first solution.

To run a local server, you have several options. I'm using Swifter, but there are other options as well: Ambassador and SBUITestTunnel.

Whatever solution you choose, the general process is as follow:

  • Pass a launch argument to identify you are running UITests
  • Catch that launch argument in application:didFinishLaunchingWithOptions:, and switch your API base URL to the one of the local server: http://localhost
  • Start your server
  • Inject your response for the URL that you are testing

You have a more detailed approach in this article for Swifter

Upvotes: 7

Oletha
Oletha

Reputation: 7639

Stubbing needs to be done in the application under test's code, rather than the test code. This is because the UI testing process does not have any control over the networking of the app under test, since they are separate from each other.

Send a launch argument when you launch the app from your test and read the launch argument in your app to invoke the stubs as part of application:didFinishLaunchingWithOptions: in your AppDelegate.

let app = XCUIApplication()
app.launchArguments = ["stub"]
app.launch()

Upvotes: 4

Related Questions