Wednesday, May 18, 2011

This Greek Tragedy

Grigoris was a man who lived a good life, made a solid name for himself, and was well-respected by his community. But now, beset by the consequences of some unfortunate, perhaps even foolish, spending habits, he found himself in a great deal of debt in his middle years.

He might have thought to change his ways and begin the ascent from debt, but as we often find, old habits are hard to break. Fortunately for Grigoris, he came from a very large family. Counting himself, there were twenty-seven siblings, amazingly, all boys and just one girl, Francesca. Grigoris appealed to his family, but they were reluctant to help, since many of them were struggling to pay their debts as well.

After a long time of appealing to his siblings and offering promises that he would change his ways, Grigoris’ brother Gregor reluctantly agreed to give Grigoris enough money to settle his debts and make a new start. Gregor hoped that someday he would be repaid, but didn’t expect it.

To no one’s surprise, Grigoris accepted the money but did not change his ways. Within a couple years, he was back in debt and once again appealing to his family for help.

Although Grigoris spent much of his money on foolishness and temporary pleasures, he managed somehow to retain a large store of family heirlooms that had great value. The family lived in constant concern that he would sell these so some unsavory neighbor, but even in the depths of his flurry of spending, Grigoris held these back.

Once again, he appealed to his family. They were no idiots, and chose not to repeat the mistake of loaning him the money. He sustained his appeal, even while the debts continued to grow. But none of his family would part with their money.

One cold spring morning a thin beam of sunlight drilled through the curtains of the room where Grigoris slept, and settled directly on his left eye, awaking him with a start, a dream still fresh in his mind. In this dream was the spark, the answer that he had desired.

He immediately came to his senses and decided what he must do. He must choose one of the heirlooms and sell it to pay off his debts. “This is what all sensible people do,” he said aloud as the light of the morning enveloped him. “Selling some precious item from my collection will be a constant reminder that I must not fall again into debt, that I must change my ways and never again shame my family in this fashion.”

And so he set out to choose one precious item, and there were many to consider. Finally, he settled on one, thinking, it must be the most precious of all. Many generations back, he knew not exactly how many, a forefather had constructed a lavish gazebo on a small piece of land on a hill from the finest marble drawn from quarries at great cost. This gazebo was a delight to the family, and many would often return home just for the purpose of seeing it once more, and spending time there. Even visitors from various places would pass by just to behold its beauty.

He must sell this.

Though wracked and distressed, he set out with determination to find a buyer. He quickly found one, a foreign man who wanted to make a tourist destination of it, a veritable circus. Should Grigoris sell to this man? Would that not compound his grief? He thought that surely none of his twenty-six siblings would ever speak to him again. Perhaps they would even disown him, sending him out from the family in disgrace.

In the end, he made the only sensible decision - he would approach his family, and ask them to buy it. To his relief, Gregor and Francesca were willing to pool their resources and purchase the prized gazebo from Grigoris. Though they were hard-pressed to afford it, they recouped their cost through reasonable and respectful marketing as a modest tourist destination.

Grigoris reformed his old foolish habits, and to his dying day, never again found himself in debt. After a long and satisfying life, he passed out of this world having won the respect of his family and all who knew him.

Monday, April 25, 2011

Using JUnit To Generate Mockito Custom ArgumentMatchers Descriptions

I'm a huge fan of Mockito. It has made our unit testing lives a veritable cakewalk for years now. There is something I'd like to be different, and that's what it provides for failure descriptions in custom argument matchers. It seems like a lot of work (well, relatively speaking) to provide a description then return false, assuming a test fails. It works out to about four lines of code for each value to be tested, if you use it something like this:

class IsPopulatedDataHolder extends ArgumentMatcher<DataHolder> {

private final int expectedValue;
private String failure;

public IsPopulatedDataHolder(int expectedValue) {
this.expectedValue = expectedValue;
}

@Override
public boolean matches(Object argument) {
DataHolder holder = (DataHolder) argument;
if(holder.getValue() != expectedValue) {
failure = "Held value does not match. Expected " + expectedValue + " but was " + holder.getValue();
return false;
}
return true;
}

@Override
public void describeTo(Description description) {
description.appendText(":" + failure);
}
}

Look at the description it builds. It looks suspiciously like a JUnit assertion message. We should let JUnit build the message for us. You can just throw the AssertionError out of matches(), but then you lose the nice Mockito-provided stack trace that hooks in with your IDE.

Have a look at this extension of the ArgumentMatcher. We'll catch the AssertionError, and stuff the message into Mockito's failure description:

public abstract class AssertConvertingArgumentMatcher<T> extends ArgumentMatcher<T> {

private String failure = null;

@Override
public void describeTo(Description description) {
description.appendText(failure);
}

@SuppressWarnings("unchecked")
@Override
public boolean matches(Object argument) {
try {
verify((T) argument);
} catch (AssertionError e) {
failure = e.getMessage();
return false;
}
return true;
}

protected abstract void verify(T argument);
}

Given this class, we can now use a JUnit Assert to build the string for us with a one-liner:

class IsPopulatedDataHolder extends AssertConvertingArgumentMatcher<DataHolder> {

private final int expectedValue;

public IsPopulatedDataHolder(int expectedValue) {
this.expectedValue = expectedValue;
}

@Override
protected void verify(DataHolder argument) {
Assert.assertEquals("Held value", expectedValue, argument.getValue());
}
}

Normally if we use an Assert in matches(), we lose the failure stack that Mockito so nicely provides for us. AssertConvertingArgumentMatcher:
  • Ties together the descriptive JUnit error with the Mockito custom matcher
  • Reduces lines to test the target code
  • Keeps intact the standard mockito stack trace (double-click drill-into-test, double-click drill-into-target)
  • Uses JUnit to build "Line width expected: <2.0> but was <1.0>," and this means no hand-coding of descriptions. JUnit builds the description for us.
  • Assert is one line instead of if(this) etc,etc
I've put some code samples here:

git://github.com/DonBranson/MockitoMatcherExamples.git