Unit Testing: Why Testing for Failures First is Good


As an experienced software developer, I consider myself extremely paranoid and cynical. Well, there’s the world-at-large aspect (which might be a bane to my existence) but there’s the software aspect, where lacking trust of what you develop is a GREAT thing. No matter how complex nor simple of an application or function you can write, the one thing that constantly should badger you is whether or not it works as intended. However, another thing you have to consider is when you think something is working as intended. You have to question even that aspect because there might be nuances that might not really be working. That’s where using failures for testing is helpful.

In TDD (Test Driven Development), it’s common to write the test case first before writing your code and making it fail. Once you have that complete, you supple the methods and code to again make it fail but you slowly get your code to work around the test case until you feel it’s ready and supply a true condition. What happens though if you didn’t start with the test case? What happens if you start with the positive case?

The problem here is that unless you’re extremely rigorous in your coding methodology, there’s a realistic chance that you won’t be creating the unit tests first. So in these cases, you still need to introduce distrust in your code, unit tests and even infrastructure at the same time. Here, you can easily create a test that will come out correct. For instance, say you were testing a method on a controller where the view outputs something simple like “test case”. If your test case just tests for the word “test” using a contains type of method, then this will work. But you still have to question whether or not this 100% is correct. What if phpunit wasn’t setup properly (i.e. you just installed it) or the web server is down. If you ran phpunit and it comes back saying everything is correct, then it’s easy to walk away, feeling confident that everything is working. And that’s where your paranoia needs to kick in.

So here, you might want to adjust your test and change the contains value from “test” to something obscure like “xyz”. Running phpunit again ought to bring up a failure. If it didn’t then something else was setup incorrectly. But at least you can pinpoint that it’s possibly your setup that is the issue.

The lesson here really isn’t a technological issue but a psychological one. It’s becoming overconfident in yourself and not having that empirical reassurance that your code is 100% as can be. Make things fail first then work towards success. Isn’t that part of how life works anyway?

(Visited 12 times, 1 visits today)

Comments

comments