Welcome Guest, Not a member yet? Register   Sign In
Unit Testing
#2

[eluser]Michael Wales[/eluser]
Each Unit Testing library handles things a bit differently, but yes you have the general "gist" of how it works. Let's say I had an accounts class and I was about to write the register() method. Before writing that method I can assert the following things (and write tests for each):

1. A unique username is required to register.
2. A unique email address is required to register.
3. A password is required to register.
5. A 5-character alphanumeric salt must be generated.

So, I'd write a test case (psuedo-code here), before ever writing my register() function:

Code:
function test_usernameValid() {
  // Build a User object that does not include a username
  // Assert that this will fail, because username is empty

  // Give that user a username
  // Assert that this will pass, because username is not-empty

  // Create a new user with the same username
  // Assert that this will fail, because username is not unique
}

Okay, so we run our tests and we see something like this:
Quote:_usernameValid(): 1 Pass, 2 Fail

What happened here was our first test we believed it would fail. But, since we haven't written any code to prevent against this test-case, it went ahead and created our user. So, we fail our test.

The second test correctly passed - just by coincidence. The third test also failed, because we believe our user will not be created when in fact, it was (because we haven't written any code to confirm uniqueness).

So, now we go and write our register() function and the first thing we do is validate against the username field - it's now required. We run our tests again:

Quote:_usernameValid(): 2 Pass, 1 Fail

Alright, our required username code is working correctly - it didn't make the user the first time, did the second, but then it did again the third (our one failure). Now, let's add some uniqueness checks to our register() method.

Quote:_usernameValid(): 3 Pass, 0 Fail

Hooray! Our code is rock-solid and we know it works (with regard to usernames). Now, write tests for all of the other situations, then write code and run tests until you pass all of them.

The good thing about tests is - what if one day your boss comes in and tells you to make some change to how users are registered. Depending on the codebase, it can be difficult to understand the ramifications of making such a change and how it will change other business process down the line. With unit tests, you can write your new code and really quick tell if your application is functioning exactly as you expect it (and how it has since the creation of the tests).


Messages In This Thread
Unit Testing - by El Forum - 11-29-2010, 02:49 PM
Unit Testing - by El Forum - 11-29-2010, 03:05 PM
Unit Testing - by El Forum - 11-29-2010, 03:31 PM
Unit Testing - by El Forum - 11-29-2010, 03:39 PM



Theme © iAndrew 2016 - Forum software by © MyBB