Reputation: 2617
I created a program to call thousands of urls, what I want to do is make sure if the url times out I can trace the timeout error back to the url. What I have in place is:
string url = "http://www.google.com";
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url);
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1";
//From Fiddler
DateTime giveUp = DateTime.UtcNow.AddSeconds(5);
if (DateTime.UtcNow > giveUp)
throw new TimeoutException("The following url could not be reached: " + url);
I want to make a unit to test that the timeout Exception works correctly. Let me know if you need more details but this should suffice.
Upvotes: 3
Views: 10812
Reputation: 122
You should have well-known results. So I see two possibilities: 1. You trust the timer-functions and use (for testing) a timeout that is an average duration (e.g. if you have durations of 40-50 ms you use 45 ms) 2. You set up your own server with simulated delays.
Upvotes: 0
Reputation: 37576
Write a setter method to the Timeout period so you can manipulate it from the Unit test, set this so short that an Exception will be thrown then Test it either using the ExpectedException attribute or in the catch statement of your Unit test to make sure such an Exception has been thrown.
Upvotes: 0
Reputation: 35870
The problem becomes what you're really testing. You could very easily spin up a little HTTP server in your test and send a request to it, knowing that it will time out--which would test your timeout code. But, you're really testing whether HttpWebRequest
correctly times out. You don't care that it correctly times out, only that it does and that you want to make sure you code handles a TimeoutException
exception.
What is usually done in this case is that a test double (mock) is used that basically just throws a TimeoutException
.
Upvotes: 8