Mahriban
Mahriban

Reputation: 41

Unit testing, assert equals if difference is not bigger than 1

Im new to Unit testing. I use Junit4, I have to compare two double numbers. But if difference is not longer than 1, it should pass. For example:

Assert.assertEquals(240, 241); //should pass
Assert.assertEquals(240, 239); //should pass

Assert.assertEquals(240, 242); //should fail
Assert.assertEquals(240, 238); //should fail

Is there way to implement it?

Upvotes: 0

Views: 767

Answers (2)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

Read the javadoc of the method you have used:

@Deprecated`  
public static void assertEquals(double expected,
                                double actual)

Deprecated. Use assertEquals(double expected, double actual, double epsilon) instead.

It tells you that this method is deprecated. And even more kindly, it tells what better method to use instead.

public static void assertEquals(double expected,
                                double actual,
                                double delta)

Asserts that two doubles or floats are equal to within a positive delta.

You see, this method exactly fits your need. So you can simply use:

Assert.assertEquals(240, 241, 1.0); //will pass
Assert.assertEquals(240, 239, 1.0); //will pass

Assert.assertEquals(240, 242, 1.0); //will fail
Assert.assertEquals(240, 238, 1.0); //will fail

Upvotes: 1

Thiyanesh
Thiyanesh

Reputation: 2360

In addition to @Nikolai Shevchenko suggestion to use Assert.assertEquals(a, b, 1.0);

Please check assertTrue too

Assert.assertTrue(Math.abs(240 - 241) <= 1)

Upvotes: 0

Related Questions