You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is a dummy example, meaning that how exactly the User and their methods are implemented does not really matter; what we actually care about here is how to test this code given the above implementation.
34
+
Say we'd like to test the `is_relative_to` method with pairs of User names and surnames using the standard `unittest` library.
35
+
So, here's an example of how we could do that as simply as possible:
36
+
## unittest
37
+
38
+
```py
39
+
from unittest import main, TestCase
40
+
41
+
42
+
classTestIsRelativeToSameName(TestCase):
43
+
deftest_same_name(self):
44
+
user1 = User("Niklas", "Strindberg")
45
+
user2 = User("Niklas", "Ibsen")
46
+
self.assertFalse(user1.is_relative_to(user2))
47
+
48
+
deftest_same_empty_name(self):
49
+
user1 = User("", "Stringberg")
50
+
user2 = User("", "Ibsen")
51
+
self.assertFalse(user1.is_relative_to(user2))
52
+
53
+
54
+
classTestIsRelativeToSameSurname(TestCase):
55
+
deftest_same_surname(self):
56
+
user1 = User("August", "Nietzsche")
57
+
user2 = User("Henrik", "Nietzsche")
58
+
self.assertTrue(user1.is_relative_to(user2))
59
+
60
+
deftest_same_empty_surname(self):
61
+
user1 = User("August", "")
62
+
user2 = User("Henrik", "")
63
+
self.assertTrue(user1.is_relative_to(user2))
64
+
65
+
deftest_same_surname_case_sensitive(self):
66
+
user1 = User("August", "NiEtZsChE")
67
+
user2 = User("Henrik", "nietzsche")
68
+
self.assertTrue(user1.is_relative_to(user2))
69
+
70
+
deftest_surname1_contains_surname2(self):
71
+
user1 = User("August", "Solzenietzsche")
72
+
user2 = User("Henrik", "Nietzsche")
73
+
self.assertFalse(user1.is_relative_to(user2))
74
+
75
+
76
+
if__name__=="__main__":
77
+
main()
78
+
```
79
+
80
+
The cases we check here are rather limited but still there is some duplication in our code; we use many lines to create our User subjects. Of course we can avoid that
81
+
by creating custom assertion methods that receive only the parameters that change
82
+
between tests, but that's why a testing library is here for.
83
+
Here's how we could write the above code with `unittest-extensions`:
The number of lines is still the same, but the testing code has become clearer:
131
+
1. The subject of our assertions in each test case is documented in the `subject` method
132
+
2. Each test method contains only information we care about, i.e. the input data (names/surnames) we test and the result of the assertion (true/false).
0 commit comments