Wednesday, June 9, 2010

Language: Unit Testing in Chinese

单元测试
Dānyuán cèshì

For a more enlishized prounounciation, "dawn yawn tsugh shh" said pretty fast

Saturday, June 5, 2010

Hello World!

In the spirit of my friend and colleague Ziroby, I've decided to start a blog on my adventures in test driven development and code katas.  In practice, I'm rather code agnostic person, but for the purpose of this blog and brevity, python will be the primary language I use.  Without further adue, I give you "Hello World Kata".  Put on your karate belts and buckle in for the ride!

import unittest

class HelloWorldTests(unittest.TestCase):
    def test_hello_world(self):
        greeter = Greeter()
        message = greeter.GetGreeting()
        expected = "Hello World!"
        assert message == expected, "How rude!"

Let's look above at our test and whats happening:

1) First we import the python unittest namespace, python 2.6 comes with its own unit testing framework already installed so don't worry about having to get it

import unittest

2) Good unit tests test to have a 3 part structure to them. This structure is called the 3 As: Arrange, Act, and Assert. Lets take a look at our arrangement:

import unittest

class HelloWorldTests(unittest.TestCase):
    def test_hello_world(self):
        greeter = helloworld.Greeter()

As you can see, arrange is simple insantiation of our greeter class.

3) Next we will perform our action:

message = greeter.GetGreeting()

4) And finally we will assert what we believe should be the result of our action:

expected = "Hello World!"
assert message == expected, "How rude!"

Note that the assertion in python is an actual keyword! Use a simple boolean logic structure, and an optional message to show if the assertion fails.

As you can imagine, our class that makes this test succeed looks something like this:

class Greeter():
    def GetGreeting(self):
        return "Hello World!"

Overkill? Perhaps. I think the lesson of this kata is to show that even our simplest of operations we can conceive of can still be unit tested and demonstrate the same qualities of unit tests for more complex systems we'll explore later!