Marius
Marius

Reputation: 837

Assert workaround in JUnit

I've seen today a non standard way of writing unit tests with JUnit,

instead of using the framework checks

Assert.assertTrue("Unexpected response encoding", text.length() >= 1);

a generic exception is thrown

if (text.length() < 1) {
    throw new Exception("Unexpected response encoding");
}

I want to to convince the author to adopt the first style. Beside reason like verbosity, clarity of intent do you know what else can differ in these approaches?

Upvotes: 0

Views: 117

Answers (3)

emory
emory

Reputation: 10891

If your primary goal is to convince someone to use the first approach over the second and you need more ammo (I agree with Jon Skeet's comment that you shouldn't need more ammo.) then use some code coverage tool over your test code.

Good developers will effortlessly get 100% coverage on their unit tests. Bad developers will not get 100% coverage without going into the if condition. Either way you can nag the bad developer. Why isn't your coverage 100%? or why do you have failing unit tests?

It s not fair, but it will motivate the desired behavior.

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 34367

Their treatment in report is different in two ways:

  1. As mentioned by @Matt, one is failure while other is error.
  2. Imagene Assert.assertEquals, when failed, it reports both expected and found values in the report along with the message.

Upvotes: 1

matt b
matt b

Reputation: 139921

JUnit reports will show the first style as a "failure" whereas the second is shown as an "error" since an uncaught exception is thrown.

It depends on if you care about this type of labeling and is completely subjective, but personally I would prefer to see this as a "failure".

Upvotes: 3

Related Questions