-
Notifications
You must be signed in to change notification settings - Fork 13
PyHamcrest
When writing tests we must maintain right balance between over-specifying the test (and making it
brittle to changes), and not specifying enough (making the test less valuable since it continues to pass even when the
thing being tested is broken). Hamcrest is a tool that allows you to pick out precisely the aspect under test and describe the values it should have. Such tests fail when the behavior of the aspect under test deviates from the expected behavior, yet continue to pass when minor, unrelated changes to the behavior are made.
Hamcrest allows checking for conditions in your code via existing matchers classes. It also allows you to define your custom matcher implementations.
We use assert_that
instead of assert as in unittest package.This new method incorporates the use of the hamcrest library and is a much improved way to write assertions. It uses what’s called matchers which are self-contained classes which have static methods that get used with the assertThat method.
eg:
Matches if object is equal to a given object.
from hamcrest import *
import unittest
class BiscuitTest(unittest.TestCase):
def testEquals(self):
theBiscuit = Biscuit('Ginger')
myBiscuit = Biscuit('Ginger')
assert_that(theBiscuit, equal_to(myBiscuit))
if __name__ == ’__main__’:
unittest.main()
More predefined Matchers can be found in the documentation
- Branch History
- Best Practices
- Testing in Python
- Logger Config
- Refactoring Suggestions