Welcome to the 3rd part of my quest to learn IronPython. In this part I’ll show how I’ve unit tested my application.
Previous parts of this series:
- Where to start – resources, environment and how I’ve started learning IronPython
- Let’s write some code – the project I’m writing along with my impressions of how things done
Being a TDD’er (Test Driven Developer) one of the first things I’ve searched from when I’ve started learning IronPython is unit testing framework, luckily for me I didn’t need to search too long.
IronPython has a good unit testing framework inherited from Python called PyUnit.
Writing unit tests using PyUnit is simple:
- import unittest class
- Create a class that inherits unittest.TestCase (test fixture)
- Write test methods using assertions methods
The following example is my first test in IronPython – check that the newly created board has two stores:
Because we’re using an open source dynamic language we have the source code for everything! Browsing the unittest.py file I found something interesting about the way assertEqual was implemented:
It seems the actual implementation is at the failUnlessEqual method:
Likewise most of the asserts actual implementation is not the assert method but the failUnless method, in fact I could have written the test above this way:
Like other unit testing frameworks there is setUp and tearDown methods as well:
I especially like the way asserting exception was thrown is done. IronPython has an assertRaises/failUnlessRaises method to check that if a specific code snippets throws exception.
Running unit tests
Writing unit tests is only half of the fun – we need to be able to run them as well.
If all of the tests are located in the same file just add this code snippet at end of the file:
When passing the test file as argument to ipy.exe all of the tests inside that file will be run:
A successful run will look like this:
If your unit tests are divided between several files you can use test suites. Read more about it in Python unit testing framework documentation.
Unit testing alternatives
While learning about PyUnit I came across other alternatives for IronPython test automation:
- Alex Henderson (Bitter Coder) has written a framework that enables writing unit tests in IronPython and running them using NUnit. you can read about it in his blog.
- python-nose – nose provides an alternate test discovery and running process for unittest. Should make writing and running unit tests easier.
My unit tests are available for download here, as always I would appreciate feedback (either comments or email).
We’re almost there – in the post in this series I plan to explain the Minimax algorithm and its implementation.