I have these values coming from a test
previousTokenValues[1] = "1378994409108"
currentTokenValues[1] = "1378994416509"
and I try
// current timestamp is greater
assertTrue(Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]));
I get the java.lang.AssertionError
and detailMessage
on debugging is null
.
How can I assert greater than conditions in using JUnit
When using JUnit asserts, I always make the message nice and clear. It saves huge amounts of time debugging. Doing it this way avoids having to add a added dependency on hamcrest Matchers.
previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";
Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);
assertTrue("Previous (" + prev + ") should be greater than current (" + curr + ")", prev > curr);
Alternatively if adding extra library such as hamcrest
is not desirable, the logic can be implemented as utility method using junit
dependency only:
public static void assertGreaterThan(int greater, int lesser) {
assertGreaterThan(greater, lesser, null);
}
public static void assertGreaterThan(int greater, int lesser, String message) {
if (greater <= lesser) {
fail((StringUtils.isNotBlank(message) ? message + " ==> " : "") +
"Expected: a value greater than <" + lesser + ">\n" +
"But <" + greater + "> was " + (greater == lesser ? "equal to" : "less than") + " <" + lesser + ">");
}
}
assertTrue("your message", previousTokenValues[1].compareTo(currentTokenValues[1]) > 0)
this passes for previous > current values
As I recognize, at the moment, in JUnit, the syntax is like this:
AssertTrue(Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]), "your fail message ");
Means that, the condition is in front of the message.
You can put it like this
assertTrue("your fail message ",Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]));
you can also try below simple soln:
previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";
Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);
Assert.assertTrue(prev > curr );
You should add Hamcrest-library to your Build Path. It contains the needed Matchers.class which has the lessThan() method.
Dependency as below.
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
Source: Stackoverflow.com