How does unit test network dependency work?

Some of my applications capture data from the Internet. I am used to writing unit tests, and I suspect that if I write a test for values ​​returned from the Internet, I will run into problems of latency and / or reliability.

What is a valid way to validate data that “lies at the other end of a web request”?

I use the stock testing toolkit that comes with Xcode, but the question is theoretically applicable to any testing framework.

+4
source share
3 answers

I asked this question to respectable people on the IRC # macdev channel on freenode.net, and I got some really good answers.

Mike Ash ( mikeash.com ) suggests implementing a local web server inside my application. For complex cases, I will probably do it. However, I just use the built-in initWithContentsOfURL:(NSURL *)url NSData method.

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

Similarly, Alistra suggests using local file URLs that point to files containing layout data.

+1
source
Test

Unit specifically geared towards the business logic of your class. There would be no latency, reliability, etc., since you would use some kind of mock object to simulate that you are actually interacting.
What you are describing is some form of integration testing, and for the OP it looks like this is not what you intend.
You have to "hide" the other end, taunting and not gaining access to the network, remote database, etc.

+2
source

Among others:

  • introduce an artificial delay 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 physically cutting the connection
  • check for incomplete data (the connection can be cut in half)
  • verification of duplicate data (the application may try to send a request more than once if it considers that it was unsuccessful - and in some cases can lead to data loss).

All of them must gracefully fail (either on the server side or on the client side).

+1
source

All Articles