Using custom asserts for better readability

Published on and tagged with refactoring  testing

Recently, I wrote the following test case for a BooleanValidator class (a class which ensures a value is of the type “boolean”):

class BooleanValidatorTest extends CakeTestCase {
    private $validator = null;
	
    public function setUp() {
        $this->validator = new BooleanValidator();
    }
	
    public function testValidate() {
        $this->assertIdentical(true, $this->validator->validate(true));
        $this->assertIdentical(true, $this->validator->validate(false));
        $this->assertTrue(is_string($this->validator->validate(0)));
        $this->assertTrue(is_string($this->validator->validate(1)));
    }
}

The code is quite trivial, though it is not that easy to see what I try to express with this code. And so we have to improve its readability.

For this purpose we will write two custom asserts. Custom asserts are nothing special, they are normal methods. But for some reason it seems like people think they always have to use the assert methods provided by the testing framework.

Let’s have a look at the test method above. What is verified in the first two lines with assertIdentical()? It is simple: it is verified the validation process recognizes the provided data as valid. So, we have the first custom assert method: assertValid().

Now you might think the second custom assert method will be assertInvalid(). This would be a good name if the validation process would return false if a value doesn’t validate. Though, in this specific case a validation error is returned, and so a better name for the second assert method is: assertValidationError().

With this, we can refactor the example from above to:

class BooleanValidatorTest extends CakeTestCase {
    private $validator = null;
	
    public function setUp() {
        $this->validator = new BooleanValidator();
    }
	
    public function testValidate() {
        $this->assertValid($this->validator->validate(true));
        $this->assertValid($this->validator->validate(false));
        $this->assertValidationError($this->validator->validate(0));
        $this->assertValidationError($this->validator->validate(1));
    }

    private function assertValid($validationResult) {
        $this->assertIdentical(true, $validationResult);
    }
	
    private function assertValidationError($validationResult) {
        $this->assertTrue(is_string($validationResult));
    }
}

The result is now much easier to read (at least in my opinion), and as a nice side effect of this refactoring we also have eliminated some duplicate code.

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License