Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Unit Tests

Name: Anonymous 2011-08-09 23:31

Can somebody explain unit testing and test driven development? I've tried to learn it through blogs and code samples and such, but I just can't grasp it. It seems like a really backwards way of writing code. I've never really had a problem learning all kinds of programming concepts and methodologies in the past but this stumps me. Is it supposed to be a really difficult thing to learn or am I just retarded?

Name: Anonymous 2011-08-10 2:15

>>1 I think you are just retarded.

Say you have a program FOO and you need to add an add() function to it.  Using TDD, you would write some unit tests for add() first, e.g.:

    is( add( 1, 1 ),    2, "add(1,1)==2" );
    is( add( -1, -1 ), -2, "add(-1,-1)==-2" );
    is( add( -1, 1 ),   0, "add(-1,1)==0" );
    isnt( add( 2, 3 ),  6, "add(2,3)!=6" );

This sets some target tests that your function must meet.  These tests should cover the requirements specified for the new function.  At this point, you have 4 unit tests which will fail (because the code doesn't exist).  Now, you write the code to make these tests pass, e.g.

    int add(int a, int b) { return a + b; }

In this contrived, small example, it is difficult to see the benefits of doing it this way, but they are roughly:

* You are more sure you are meeting the specifications.
* You don't entirely skip writing the tests in a time crunch, which is easy to do, but unit testing is very important, and gives you confidence that your code is correct and makes it so that sweeping changes or refactoring your code later is much easier.
* In more complex feature additions, if you are sure your tests are correct and cover the specs, if your first one or two tries adding the features don't pass the tests, you can just delete your attempt and start over from scratch, instead of painstakingly debugging your code.  Debugging will always necessary, but if you can minimize the time spent doing so by working smarter, you can be more productive overall.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List