tags:

views:

51

answers:

6

Should I be writing
assertTrue("User logged in", user.isLoggedIn());
or
assertTrue("User is not logged in", user.isLoggedIn());

The former provides better reading inside the source files:
"I assert that the following is true: User logged in."

The error message could be read both ways:
java.lang.AssertionError: User logged in
"There is an error in asserting that the user is logged in"
"The error is that the user is logged in."

JUnit documentation doesn't provide a clear guide to which it should be, except it is
"the identifying message for the {@link AssertionError}",
And in both cases, the text identifies the test being run.

What's the common usage?

+4  A: 

How about:

assertTrue("User should be logged in", user.isLoggedIn());

Works both ways.

Matthew Wilson
I like this, short but to the point.
Steve
+2  A: 

Well, you could also state your assumption, and then how the assumption didn't hold. Like so:

assertTrue("Expected user to be logged it, and wasn't", user.isLoggedIn());

Makes for clearer messages, but longer to type and read.

jjnguy
+1, it's absolutely worth being as clear as possible - when a failure pops up in the midst of many hundreds of tests you want as much context as possible to help you get your head into the reason for it
Brian
A: 

You should include both cases. You have better test case when you triangulate your assertions.

Haoest
A: 

To avoid that question, I more and more tend to use assertThat instead of "low-level" assert* methods. Indeed, like this article explains, assertThat will give you a very clear error message in case of failure.

Riduidel
A: 

You could use :

assertTrue("Test if user is logged in", user.isLoggedIn());

When you do this, you're verifying that user.isLoggedIn() is true, you can't really say that user is logged in or not, you don't know yet, you're just testing it.

Colin Hebert
A: 

Interesting, I would use:

assertTrue("user should be logged in", user.isLoggedIn());

which tells me what is expected state of this assertion.

I think the best choice is the one you understand.

Simon