Tests – enforce behavior with your unit tests

What should be your guidelines when writing tests? Especially these targeting “simple behaviors”?

I’ve just finished working on a bug – some function raised an error we didn’t take care of, so I added a proper handling mechanism. Next thing I need is to get my code approved in order to merge it into master.

My code:

public void SomeFunction()
        Foo(); // function which throws an unhandled exception
    catch (SomeException ex)
        // handling exception

“You need to add a test.”

It caught me a little off guard. The file I worked on already has unit tests, which I made sure still pass even after my changes. So what exactly should I check?

You might have guessed it. The test should mock a case where calling Foo results in SomeException, and verify it was indeed caught.

But why? Why should I do it? Of course it will be caught! What exactly are we checking here, the C# language?

Here lies a great principle in working on a large code base. The test I wrote wasn’t needed just for testing behavior. It was needed to enforce behavior. In case any other programmer working on the code base in the future will change something, the test will be there in our stead to keep them from changing already-implemented functionality!

“Good programmers shouldn’t break stuff.”

Yes, of course they shouldn’t. However, if something can go wrong, given enough time it certainly will. Our tests should aspire to make it impossible to change code in a way that will break something we wrote.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: