1.2 Creating Unit Tests in Python

In this lesson, I’ll show you how to use unittest, the built-in Python testing framework. Follow along and you’ll see how easy it is to get started writing unit tests in Python.

Code Snippet

The following snippet shows the simplest kind of test. It passes if the calculator add method computes the correct result.

def test_adds_two_numbers(self):
  self.calculator.add(1,1)
  self.assertEqual(self.calculator.total, 2)

The following snippet shows how to create a test that expects failure. It will pass if an exception is raised.

@unittest.expectedFailure
def test_divide_two_numbers(self):
  calculator = Calculator()
  calculator.divide(1,0)

Related Links

1.Taming Python With Unit Tests
2 lessons, 09:22

Free Lesson
1.1
Introduction
01:13

1.2
Creating Unit Tests in Python
08:09