Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

ios - How do I mock network requests in Xcode UI tests while the tests are running?

We've got a suite of UI tests for our app written using KIF which I'd like to convert to use the new Xcode UI test framework.

The app is a client of a Rest AI whose responses we're currently mocking by using NSURLProtocol to serve predefined JSON files in response to the GETs, POSTs, PUTs, etc... All the tests are defined using the data in these files, so I want to continue using them. The same endpoints on the server return different data at different points in the tests, so I can't mock them up-front, I need to be able to call a method while the test is running to mock the server's next response.

Unfortunately, using NSURLProtocol inside an Xcode UI test doesn't affect the tested app, and I've only seen ways of sending data to the app via launch arguments or environment, such as in this answer. I need to mock them differently at different stages during my tests. How can I mock network requests from inside the UI test in a way that changes during the test? Or how can I communicate with the app being tested so I can get it to mock the requests itself?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We've developed an embedded HTTP server in pure Swift, you can run the HTTP server with simple mock response handler in your test case, then pass the URL to the target app via environment variable like API_BASE_URL. I wrote an article about how to do it

Embedded web server for iOS UI testing

Basically there are two libraries, one is Embassy, it's the simple async HTTP server. Another one is Ambassador, a simple web framework for mocking API endpoints.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...