Section 8.3 Arrange, Act and Assert
It is time for us to write our first test. And to do that, we need to first understand the three part of any unit test.
- Arrange is first. In the arrange part we set up the system, we bring it to a state where it is ready to be tested. In this part we typically create some objects: the object that we want to test and possibly other objects needed in the process. For example if we wanted to test the
Summary
class, we would need to create aSummary
object. And in order to do that we need to provide it with aGradeReader
instance, and to get that we need aScanner
, which we can base off of reading aString
. All these would need to be created in order for us to start the test. - Act is the next phase. This phase typically consists of a single step: Calling the function that you are trying to test, and storing its result, if it had any. For instance that might mean calling the
invoke
method. - Assert is the final phase. After the method has been called, we need to verify that the correct thing happened. This might involve looking at the result of the act call, looking at changes that might have happened in the
Summary
object etc. We verify that what should have happened did indeed happen. This may include a singleassertEquals
or multiple assert calls, that collectively check that the system is as it should be; this is often called a single logical assertion.
In general we follow the so-called single assert rule:
Single Assert Rule. Each test should have a single act-assert pair.
What we want to avoid is a situation where we perform an act followed by an assert, and then followed by another act part and a second assert part. These test a different invocation and should probably have their own dedicated test.
There is one notable exception to this rule:
Tests that test simple input-output methods with no side-effects may place in a single test alternative inputs of the same type.
For example in a few moments we will write our first test, to test that a grade based off a letter has the correct points corresponding to that letter. While a few representative letters might work, ideally we should test all the standard letters we want to support, about 12 of them. We can place those 12 cases in a single test if we can make it clear enough, because they simply involve creating a new
Grade
object and accessing its getPoints
method. We’ll see this in action shortly.