Arrange Act Assert

"Arrange-Act-Assert"
a pattern for arranging and formatting code in UnitTest methods:
Each method should group these functional sections, separated by blank lines:
  1. Arrange all necessary preconditions and inputs.
  2. Act on the object or method under test.
  3. 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:


See Also:


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.

-- JeffGrigg


EditText of this page (last edited July 12, 2012) or FindPage with title or text search