Why I use .test domains in my unit tests
| 1 minute readWhen writing unit tests it's often necessary to have some test URL in your test data that you don't intend to ever be actually used. For example the profile picture URL on a user profile.
For this kind of thing I almost always use a domain under the .test top level domain (TLD). For
example https://coolimages.test/picture.jpg.
What even is that
The .test TLD (along with .example, .invalid and .localhost) is defined in
RFC 2606 as being reserved for testing, documentation and examples.
Meaning nobody can ever register a real domain under any of those TLD's.
Why it can actually matter
Maybe your unit test was never supposed to fetch data from that test URL, but we all make mistakes, especially in large systems where it's hard to trace all the data flows.
The benefit of using a .test domain is that it will always fail at the DNS level, usually with a
very clear message like this example from curl:
curl: (6) could not resolve host: coolimages.test
When you see something like that it's super obvious that some piece of code is using a URL it's not supposed to and you can go fix it.
If it is a real URL maybe some code just makes a request to it, if that request works maybe you don't even notice anything other than your test being a little slow, until that site goes down or someone deletes something from it.
Something similar to this actually happened at my place of work where all of our builds failed because some old test was using a flickr image URL which suddenly started returning a 403, presumably because the image was made private.
Who knows how many thousands of times those tests downloaded that one image from flickr over the years.
Conclusion
In conclusion, failing fast is pretty good.