Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert greater than using JUnit Assert?

Tags:

java

junit

People also ask

How do you know if greater than assert?

The assertGreaterThan() function is a builtin function in PHPUnit and is used to assert whether the actual value is greater than the expected value or not. This assertion will return true in the case if the actual value is greater than the expected value else returns false.

Is assertThat actual is Equalto expected ))) a valid Hamcrest assert statement?

assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.

What is assertThat in JUnit?

The assertThat is one of the JUnit methods from the Assert object that can be used to check if a specific value match to an expected one. It primarily accepts 2 parameters. First one if the actual value and the second is a matcher object.


Just how you've done it. assertTrue(boolean) also has an overload assertTrue(String, boolean) where the String is the message in case of failure; you can use that if you want to print that such-and-such wasn't greater than so-and-so.

You could also add hamcrest-all as a dependency to use matchers. See https://code.google.com/p/hamcrest/wiki/Tutorial:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

assertThat("timestamp",
           Long.parseLong(previousTokenValues[1]),
           greaterThan(Long.parseLong(currentTokenValues[1])));

That gives an error like:

java.lang.AssertionError: timestamp
Expected: a value greater than <456L>
     but: <123L> was less than <456L>

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);

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>