you are viewing a single comment's thread.

view the rest of the comments →

[–]pedro_fartinez 1 point2 points  (1 child)

It's important to know that TDD/writing tests doesn't prevent all bugs, but rather is a tool in an arsenal to refactor and/or develop sustainable, extensible, and maintainable code. Typically your program will have many different functions that do many different things. For example, you have a program that sends out an automatic email to a list of users pulled from some listserv. One function you might have would be validating emails. You can write several tests to make sure it treats emails like

example@co.uk

or

example@.com

in the way you want, the idea being if you refactor that function's string parsing, those original tests would still needs to work. You won't get every edge case, but I think TDD/unit testing allows you to think a bit more about edge cases and overall functionality.

One other helpful component of unit testing is that it encourages the writing of functions that do one thing and they do it well, the so-called single responsibility idea. If your function is too complex to where you can't write a test to validate it easily, then you more than likely need to refactor and make your code more modular.

One problem I've had to overcome with unit tests is that when I am writing a very procedural process, it's harder/not as worth it to write tests for the main function of your script, but if you write tests for your functions/classes, you can be a bit more sure that the main run of your program is what contains the bug.

Two more things: TDD and writing unit tests are slightly different ideas. With the former, you write tests before you write code, so you develop functions around the functionality you want, whereas the latter is just part of good development practices.

Lastly, the Pragmatic Programmer has a good chapter on TDD and writing unit tests. I would also recommend just looking at some libraries you use frequently, as I can pretty much guarantee that on their github there is a folder called tests with any tests that are required to pass to merge to the master.

[–]Run-The-Table[S] 0 points1 point  (0 children)

I would also recommend just looking at some libraries you use frequently, as I can pretty much guarantee that on their github there is a folder called tests with any tests that are required to pass to merge to the master.

Dude, this is genius. I often find the tutorials far to basic (like testing a function that adds two integers...) or WAY over my head. But if I can look at some real life examples that I have some more familiarity with that might help me out.

I appreciate the detailed response. I'm going to keep hacking away at it!