Mockito - 验证双精度值 [英] Mockito - verify a double value

查看:62
本文介绍了Mockito - 验证双精度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 method1 的方法,它接受一个在 myManager 上调用的 double我正在传递这个 65.888 * 60.当我尝试验证这个时,我遇到了浮点问题.验证失败.预计 3953.28 但 3953.280029296875

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

无论如何我可以让这个验证对浮点检查进行模糊检查.就像你在 assertEquals 中所做的一样,你在最后输入一个增量.

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.

谢谢

推荐答案

您可以捕获值,例如

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

然后断言:

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

更新:

您可以使用 AdditionalMatchers.eq(double, double) 代替,例如:

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

尽管明智地使用 AdditonalMatchers 匹配器,根据文档:

Although use AdditonalMatchers matchers wisely, as per the documentation:

AdditionalMatchers 提供了很少使用的匹配器,保留只是为了与 EasyMock 稍微兼容.非常明智地使用额外的匹配器,因为它们可能会影响测试的可读性.建议使用 Matchers 中的匹配器,并保持存根和验证简单.

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.

这篇关于Mockito - 验证双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆