Over Exertion Assertion

5d20104659a765ecf2fd326d383bea98_people-gym-icon-working-out-clipart-transparent_512-512

Imagine finding this in a unit test:

List results = service.getFoosInOrder();

int previousOrder = results.get(0).getOrdering();
for(int i=0; i= because they can sometimes be of same value
  if (!(ordering>=previousOrder)) {
    Assert.fail("Not in ascending order");
  }
  previousOrder = ordering;
}

I wish that I had invented the above example from my imagination. Unfortunately, it’s only a slight exaggeration of something I found SEVERAL TIMES OVER in some test code I was working with.

What’s wrong with the above?

– What’s it doing? I think we can guess, but we’re not 100% sure
– Does it have a bug in the assertion? Possibly a few.
– Is it going to be pasted into other tests that want to check the ordering of a list? Yup, it probably is!
– Does it add robustness/meaning to the tests – nope!

The above is an example of an assertion that requires too much coding to be used in a test just like that.

Ideally such an assertion should be moved into (or imported from) an assertion library where it can also be EXHAUSTIVELY tested.

The target test would then read:

assertInOrder(service.getFoosInOrder(),
    Foo::getOrdering, ASCENDING_OR_EQUAL);

I imagine that you could work out how to write such a reusable assertion, and
I imagine when that’s all you were writing, you wouldn’t get confused about how
to handle indices in a list you were comparing pairwise.

When you find an assertion algorithm in a test, it’s time to find a way to move that into a crisp self-describing assertion method, ideally well-tested and in a library somewhere.

Advertisements

One comment

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 )

Google+ photo

You are commenting using your Google+ 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