Triple A for Tight Tests – The Code
Agile
in a Flash by Jeff Langr and Tim Ottinger (card #46)
> Arrange all the things
needed to exercise the code
> Act on the code you want to
verify
> Assert that the code worked
as expected
--
Arrange-Act-Assert (AAA), a
simple concept devised by Bill Wake of xp123.com, provides subtle power by
helping test readers quickly understand the intent and flow of a test. No more
“What the heck is this test even testing?”
In a unit test, you first create,
or arrange, a context; then execute,
or act on, the target code; and
finally assert that the System Under
Test (SUT) behaved as expected. Thinking in terms of AAA has direct impact on
the code’s visual layout.
The simplest (perhaps ideal) test
has three lines, one for each A. Here’s an example where we must verify that
the SUT applies late fines to a library patron:
@Test
public void applyFine() {
Patron
patron = new Patron(); // arrange the context
patron.setBalance(0);
patron.applyFine(10);
// act
assertEquals(10,
patron.fineBalance()); // assert
}
You don’t need the comments—the
blank lines alone are sufficient.
AAA (also known as
given-when-then) isn’t an absolute rule. You might not need an Arrange, and
it’s OK to combine an Act and an Assertion into a single-line test.
“Reliability is the degree to which an assessment tool produces stable and consistent results” ~ Phelan, C & Wren, J. (http://www.uni.edu/chfasoa/reliabilityandvalidity.htm)
http://www.guru99.com/testing-methodology.html
No comments:
Post a Comment