Gary Gregory
Gary Gregory

Reputation: 546

Nice pattern for evaluating an assert message after a test fails

Let's say I have a JUnit test like:

Assert.assertTrue(complexResult.toString(), someMethod(in1, in2, complexResult)

If the test fails, my message will be a complexResult string BEFORE the interesting part of the test that calls someMethod, not the string view of my complexResult after the test failed.

Is there a better way than:

if (!someMethod(in1, in2, complexResult)) {
   Assert.fail(complexResult.toString());
}

?

Upvotes: 0

Views: 47

Answers (2)

gandaliter
gandaliter

Reputation: 10101

Yes, just pre-evaluate the parameter of the assert call.

boolean result = someMethod(in1, in2, complexResult);
Assert.assertTrue(complexResult.toString(), result);

This is more elegant than the fail approach.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691715

boolean result = someMethod(in1, in2, complexResult); 
assertTrue(complexResult.toString(), result);

Upvotes: 2

Related Questions