- "Arrange-Act-Assert"
- a pattern for arranging and formatting code in UnitTest methods:
Each method should group these functional sections, separated by blank lines:
- Arrange all necessary preconditions and inputs.
- Act on the object or method under test.
- Assert that the expected results have occurred.
ToDo: See AssembleActivateAssert (and consider condensing!)
Examples:
@Test
public void test() {
String input = "abc";
String result = Util.reverse(input);
assertEquals("cba", result);
}
Benefits:
- Clearly separates what is being tested from the setup and verification steps.
- Clarifies and focuses attention on a historically successful and generally necessary set of test steps.
- Makes some TestSmells? more obvious:
- Assertions intermixed with "Act" code.
- Test methods that try to test too many different things at once.
See Also:
- http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html - "Principles for Test-Driven Development" #5: "Follow the "3-As" pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As. Arrange is variable declaration and initialization. Act is invoking the code under test. Assert is using the Assert.* methods to verify that expectations were met. Following this pattern consistently makes it easy to revisit test code."
This does not apply so much to DesignByContract. Then you Specify your contract, Arrange, Act. The DbC system will then fail the test if the contract is violated.
-- AnonymousDonor
People tell me that Arrange-Act-Assert fails when using some MockObjectTestingFrameworks too, because some such frameworks typically require that you specify expected behavior before calling the code under test. So MockObject specs are given in the "Arrange" section, leaving "nothing" for the "Assert" section. (EasyMock fits this description but not Mockito. Mockito differs in that it has a verify section at the end that meets the Assert requirement, although it refers to the pattern as given/when/then.)
However, even when all contracts and specifications are given in the "Arrange" section, it's often necessary to put a single ".verify()" call after the production code "Act", so that the framework can verify that all the expected method calls were made. (IE: That none were missed.)
And even if we end up with tests lacking Arrange or Assert code occur, I don't find this to be a significant problem.
- Some tests lack an Arrange section because no setup is needed, or all necessary setup has been refactored out into the setUp method and/or field initializers.
- Some tests lack an Assert section because the intent of the test is to assert that the CodeUnderTest? (in the Act section) does NOT throw an exception.
--
JeffGrigg