I'm new to unit tests for my own projects, so this is my first attempt to write a unit test from scratch. I'm using python, and the unittest module. The TodoList class being tested here is a wrapper for actual lists, with a few extra methods for stuff like saving to disc. It also defines a few methods for getting items by their ID in the list (which isn't the same as the list index).
Tests (I've cut out a few helper methods, and a good few tests for the sake of not having people to scroll forever):
class TodoListTests(unittest.TestCase):
def setUp(self):
self.testdata = open("./testdata.json", "r")
self.testdata_text = self.testdata.read()
self.testdata.close()
def tearDown(self):
try:
os.remove("./todo.json")
except OSError:
# File not created, no need to delete.
pass
def create_todolist_and_safe_list(self):
self.create_data_file()
self.todolist = todolist.TodoList("./todo.json")
self.list = json.loads(self.testdata_text)
def create_data_file(self):
datafile = open("./todo.json", "w")
datafile.write(self.testdata_text)
datafile.close()
# Snip out a few more helper methods
def test_loop(self):
self.create_todolist_and_safe_list()
test_list = []
for item in self.todolist:
test_list.append(item)
self.assertEquals(test_list, self.list)
def test_save(self):
self.create_todolist_and_safe_list()
self.todolist.save()
newfile_text = self.get_data_file_as_string()
self.assertEquals(newfile_text, self.testdata_text)
# Snip out the rest of the tests.