DEV Community

Discussion on: ELI5: Useful Unit Testing

Collapse
 
bcgoss profile image
Bryan Goss

Every piece of software is tested. The most common form of testing is for the person who wrote it to give it a spin to see if it works. Any time I make a change I could spend time (more and more time as my program grows) checking every corner. Instead, unit tests and integration tests can give me confidence that the program still behaves the way I intend it to in a few seconds or a couple minutes.

In a small, one person project you might decide testing with your eyeballs is good enough. As the size of your project grows consider writing tests that mirror the steps you would manually do to check your code. When you change something run the tests to check that your change didn't effect something it's not supposed to.

On a large project there's no way to test with your eyeballs without missing something. In that case more and more tests are needed. If your application makes money the need for confidence in it working as expected grows.

Test first is the only way I know how to get really good test coverage that really demonstrates my software will do what I think it's supposed to do. If I write tests after finishing my work I'll be tempted to say the feature is small or simple or not with testing. I'm probably never coming back to fill in missing tests, so I should write them first for everything.

So what to test? I test that for a normal input (pick one you'd use if you manually checked it) I can get a normal output. If there are side effects, (http request, database records, output on the screen) check that they seem normal. Next if there's more than one path through the code under test make sure each path has one test with normal inputs for that path. Finally think of common failures like http problems, user input with typos or emoji or a precondition not met. Don't stress about covering every possible failure, add these as they happen and you handle them. Over time your tests will check for problems you forgot about.

The end goal is that you run your test suite and it checks everything you would spend all afternoon looking over, in a matter of seconds. Then you make a change, run your tests and trust that they will fail if your program behaves incorrectly

Collapse
 
deciduously profile image
Ben Lovy

I think test first sounds like a good exercise, it might uncover a lot of these answers to step though the process myself. Thinking about it as self-automation makes a lot of sense! Thank you for the thorough response.

Collapse
 
bcgoss profile image
Bryan Goss

I used exercism.io to practice using test first or test driven design. They probably have programming challenges in a language you're interested in and they pair you with a mentor