Source From Here
What is Arrange Act Assert?The “Arrange-Act-Assert” (also AAA and 3A) pattern of testing was observed and named by Bill Wake in 2001. I first came across it in Kent Beck’s book “Test Driven Development: By Example” and I spoke about it at PyConUK 2016.
The pattern focuses each test on a single action. The advantage of this focus is that it clearly separates the arrangement of the System Under Test (SUT) and the assertions that are made on it after the action. On multiple projects I’ve worked on I’ve experienced organised and “clean” code in the main codebase, but disorganisation and inconsistency in the test suite. However when AAA is applied, I’ve found it helps by unifying and clarifying the structure of tests which helps make the test suite much more understandable and manageable.
Background
I’ll now go into detail on each of these parts using Pytest and a toy test example - a simple happy-path test for Python’s builtin list.reverse function. I’ve made the following assumptions:
This post is only an introduction to the AAA pattern. Where certain topics will be covered in more detail in future posts in this series, I have marked them with a footnote.
Definition
The definition of the test function.
Example
- def test_reverse():
Docstring
An optional short single line statement about the behaviour under test.
Example
- """
- list.reverse inverts the order of items in a list, in place
- """
Docstrings are not part of the AAA pattern. Consider if your test needs one or if you are best to omit it for simplicity. If you do include a docstring, then I recommend that you:
Arrange
The block of code that sets up the conditions for the test action.
Example
There’s not much work to do in this example to build a list, so the arrangement block is just one line.
- greek = ['alpha', 'beta', 'gamma', 'delta']
Act
The line of code where the Action is taken on the SUT.
Example
- result = greek.reverse()
Assert
The block of code that performs the assertions on the state of the SUT after the action.
Example
- assert result is None
- assert greek == ['delta', 'gamma', 'beta', 'alpha']
The final test
Here’s the example test in full:
- def test_reverse():
- """
- list.reverse inverts the order of items in a list, in place
- """
- greek = ['alpha', 'beta', 'gamma', 'delta']
- result = greek.reverse()
- assert result is None
- assert greek == ['delta', 'gamma', 'beta', 'alpha']
Check out flake8-aaa - a Flake8 plugin that makes it easier to write tests that follow the Arrange Act Assert pattern outlined above.
沒有留言:
張貼留言