|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +import unittest |
| 4 | + |
| 5 | +from dft.parameter_injection import TimeDisplay, MidnightTimeProvider, ProductionCodeTimeProvider, datetime |
| 6 | + |
| 7 | +""" |
| 8 | +Port of the Java example of "Parameter Injection" in |
| 9 | +"xUnit Test Patterns - Refactoring Test Code" by Gerard Meszaros |
| 10 | +(ISBN-10: 0131495054, ISBN-13: 978-0131495050) accessible in outdated version on |
| 11 | +http://xunitpatterns.com/Dependency%20Injection.html. |
| 12 | +
|
| 13 | +Test code which will almost always fail (if not exactly 12:01) when untestable |
| 14 | +production code (have a look into constructor_injection.py) is used: |
| 15 | +
|
| 16 | + def test_display_current_time_at_midnight(self): |
| 17 | + class_under_test = TimeDisplay() |
| 18 | + expected_time = "24:01" |
| 19 | + result = class_under_test.get_current_time_as_as_html_fragment() |
| 20 | + self.assertEqual(result, expected_time) |
| 21 | +""" |
| 22 | + |
| 23 | +class ParameterInjectionTest(unittest.TestCase): |
| 24 | + |
| 25 | + def test_display_current_time_at_midnight(self): |
| 26 | + """ |
| 27 | + Would almost always fail (despite of right at/after midnight) if |
| 28 | + untestable production code would have been used. |
| 29 | + """ |
| 30 | + time_provider_stub = MidnightTimeProvider() |
| 31 | + class_under_test = TimeDisplay() |
| 32 | + expected_time = "<span class=\"tinyBoldText\">24:01</span>" |
| 33 | + self.assertEqual(class_under_test.get_current_time_as_html_fragment(time_provider_stub), expected_time) |
| 34 | + |
| 35 | + def test_display_current_time_at_current_time(self): |
| 36 | + """ |
| 37 | + Just as justification for working example with the time provider used in |
| 38 | + production. (Will always pass.) |
| 39 | + """ |
| 40 | + production_code_time_provider = ProductionCodeTimeProvider() |
| 41 | + class_under_test = TimeDisplay() |
| 42 | + current_time = datetime.datetime.now() |
| 43 | + expected_time = "<span class=\"tinyBoldText\">{}:{}</span>".format(current_time.hour, current_time.minute) |
| 44 | + self.assertEqual(class_under_test.get_current_time_as_html_fragment(production_code_time_provider), expected_time) |
| 45 | + |
0 commit comments