使用Mockito检查多个参数的一致性 [英] Checking consistency of multiple arguments using Mockito

查看:137
本文介绍了使用Mockito检查多个参数的一致性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mockito来模拟一个类,该类的方法如下所示:

I'm using Mockito to mock a class that has a method that looks something like this:

setFoo(int offset, float[] floats)

我希望能够验证数组(floats)中的值是否等于(在给定的公差范围内)期望值数组中的值.

I want to be able verify that the values in the array (floats) are equal (within a given tolerance) to values in an array of expected values.

问题是我想从offset指定的位置开始检查floats的内容.为了测试的目的,我不知道/不在乎偏移量是什么,只要它指向我期望的值即可.我也不在乎数组的其余部分.我只关心从提供的偏移量开始的值.

The catch is that I want to check the contents of floats starting at the position specified by offset. For the purposes of the test I don't know/care what the offset is as long as it points at the values I'm expecting. I also don't care what the rest of the array contains. I only care about the values starting at the supplied offset.

我该怎么做?

推荐答案

虽然部分模拟并不是一个坏主意,但是如果使用

While a partial mock isn't a bad idea, you might find your code easier to follow if you use an ArgumentCaptor instead to get the values after the fact. It's a special argument matcher that keeps track of the value it matches.

// initialized with MockitoAnnotations.initMocks();
@Captor ArgumentCaptor<Integer> offsetCaptor;
@Captor ArgumentCaptor<float[]> floatsCaptor;
@Mock Bar bar;

@Test
public void valuesShouldBeCloseEnough() {
  Sut sut = new Sut(bar);
  sut.doSomething();
  verify(bar).setFoo(offsetCaptor.capture(), floatsCaptor.capture());

  // check values with assertValuesAreCloseEnough, declared elsewhere
  assertValuesAreCloseEnough(offsetCaptor.getValue(), floatsCaptor.getValue());
}

这篇关于使用Mockito检查多个参数的一致性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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