4

Some of my apps grab data from the internet. I'm getting into the habit of writing unit tests, and I suspect that if I write a test for values returned from the internet, I will run into latency and/or reliability problems.

What's a valid way to test data that "lies on the other end of a web request"?

I'm using the stock unit testing toolkit that comes with Xcode, but the question theoretically applies to any testing framework.

Moshe
  • 57,511
  • 78
  • 272
  • 425

3 Answers3

3

Unit test is focused specifically on the business logic of your class. There would no latency, reliability etc as you would use some mock object to simulate what you actually interact.
What you are describing is some form of integration testing and for the OP seems like is not what you intent.
You should "obscure" the other end by mocking and not really access the network, a remote database etc.

Cratylus
  • 52,998
  • 69
  • 209
  • 339
1

Among others:

  • introduce artificial latency in requests
  • use another machine on the same network or at least another VM
  • test connection failures (either by connecting to a non existent server or cutting physically the connection
  • test for incomplete data (connection could be cut half way)
  • test for duplicate data (app could try to submit the request more than once if it thinks it was not successful - and in some scenarios may lead to lost data)

All of these should fail gracefully (either on the server side or on the client side)

Youn Elan
  • 2,379
  • 3
  • 23
  • 32
1

I posed this question to the venerable folks on #macdev IRC channel on freenode.net, and I got a few really good answers.

Mike Ash (of mikeash.com) suggests implementing a local web server inside my app. For complex cases, I'd probably do this. However, I'm just using some of the built in initWithContentsOfURL:(NSURL *)url method of NSData.

For simpler cases, mike says an alternate method is to pass base64 encoded dummy data directly to the NSData initializer. (Use data://dummyDataEncodedAsBase64GoesAfterTheDataProtocolThingy.)

Similarly, "alistra" suggests using local file URLs that point to files containing mock data.

Moshe
  • 57,511
  • 78
  • 272
  • 425