RNJ
RNJ

Reputation: 15552

Mockito - verify a double value

I have a method called method1 that takes a double which is called on myManager I am passing into this 65.888 * 60. When I try and verify this I get floating point problems. The verification fails. It expects 3953.28 but 3953.280029296875

verify(myManager, times(1)).method1(65.888 * 60d);

Is there anyway I can make this verify do a fuzzy check for floating point checking. Much like you do with assertEquals where you input a delta at the end.

Thanks

Upvotes: 20

Views: 13275

Answers (3)

Jonathan
Jonathan

Reputation: 20375

You could capture the value, e.g.

final ArgumentCaptor<Double> captor = ArgumentCaptor.forClass(Double.class)
...
verify(myManager).method1(captor.capture());

Then assert:

assertEquals(expected, captor.getValue(), delta)

Or, perhaps, use an argument matcher which does the assertion:

verify(myManager).method1(doubleThat(new ArgumentMatcher<Double>() 
{
    @Override 
    public boolean matches(final Object actual)
    {
        return Math.abs(expected - (Double) actual) <= delta;
    }
}));

Update:

Instead of using either of the methods above, you could use AdditionalMatchers.eq(double, double) instead, e.g.:

verify(myManager).method1(AdditionalMatchers.eq(expected, delta));

Although use AdditonalMatchers matchers wisely, as per the documentation:

AdditionalMatchers provides rarely used matchers, kept only for somewhat compatibility with EasyMock. Use additional matchers very judiciously because they may impact readability of a test. It is recommended to use matchers from Matchers and keep stubbing and verification simple.

Upvotes: 30

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79867

There is a Hamcrest matcher that is perfect for this.

org.hamcrest.Matchers.closeTo(value, error)

So you could write something like

verify(myManager).method1(doubleThat(org.hamcrest.Matchers.closeTo(65.888 * 60, 0.001)));

Incidentally, you don't ever need to write times(1) in a Mockito verify, as this is the default type of verify that Mockito gives you.

Upvotes: 10

Christian
Christian

Reputation: 4094

Following code works for me:

private class MockedClass {
    public void method1(double d) {}
}

@Test
public final void testMockito() {
    MockedClass d = mock(MockedClass.class);
    d.method1(3953.28);
    verify(d, times(1)).method1(65.888 * 60d);
}

Maybe you should instead call the method with anyDouble() or use following Matcher: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/number/IsCloseTo.html

Upvotes: 1

Related Questions