How to Write Code to BeforeAll, BeforeEach etc
The full code can be found in SampleBeforeAfterTester.
BeforeAfter Code
This CustomBeforeAfterTester uses all four methods. The variables a
and b
are not declared in the class, because they are needed in the actual tests. As a result, they are declared as global private variables.
The beforeAll()
method starting at line 3 is only for explicit instantiation of the integers. If not explicitly set, they will be 0 anyway.
In the beforeEach()
method starting at line 8 we increment a
. In the afterEach()
method starting at line 12 we increment b
.
Finally, we use the afterAll
to print out a
and b
.
Test Code
In line 1 we just create a TestSuite without a TestRunner, because we are only running a single test suite. In line 2 we create a instance of the custom BeforeAfter class, and in line 4 we add it to the test suite. Now we are ready to start running tests. Many of the tests are straightforward, but some deserve further comment.
On lines 16 and 17 we create a double to pass to the assertEqualsDouble()
. This is because we cannot just pass 3.0
. We could use assertEqualsNumeric()
, which proxies off to assertEqualsDouble()
, but on this occasion we're using the lower level assertion.
Note on line 18 we compare b
. If we were to test a
, we would need to expect the value to be 3, not 4. This is because, although the CDbl()
function is inside the assertion, it is executed before the assertion - and thus before the beforeEach()
is triggered. The result of the executation passed to the assertion, at which point the beforeEach()
will run. As a result, for ease of fourth-dimensional thinking, we just compare against the value modified in the afterEach()
function.