Asserts and testing


Miško Hevery over at the Google Testing Blog has a few things to say about Asserts and testing. He's against asserts, specifically ones which perform null checks, as they get in the way of testing. Whilst I agree with his dislike of assertions (see here) I disagree with his dislike of null checks...

Miško complains that by having an object check passed in objects for null and assert if they are this causes him problems in testing where he knows that he doesn't need the objects that are being passed in to test the functionality that he's testing. He prefers to pass null for these objects and the assertions get in the way. Personally I'd prefer to pass in mock objects for the objects that aren't used and then validate that they're not used during the test. This would allow any null checks to remain in the code.

Obviously we're working in different languages here but in C++ I'd design the code to make it impossible to pass in a null pointer for non-optional objects. Instead I'd make my intent clear to the caller by taking a reference rather than a pointer; in C++ a reference can't be null (unless you do very bad things to circumvent the language). This removes most, if not all, of the kind of assert that Miško objects to from my code but doesn't solve his problem; I've just forced him to pass in valid objects... As I said above, he can use mocks for these.

Leave a comment