I'm using Mockito to mock a class that has a method that looks something like this:
setFoo(int offset, float[] 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.
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.
How do I do this?
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());
}
You want a partial mock. Let's assume that the class that has setFoo()
is named Bar:
private static abstract class AssertingBar implements Bar {
@Override
void setFoo(int offset, float[] floats) {
this.offset = offset;
this.floats = floats
}
public void verify(float[] expectedFloats, float delta) {
// do your verification here
}
}
@Test
public void valuesShouldBeCloseEnough() {
AssertingBar bar = Mockito.mock(AssertingBar.class, Mockito.CALLS_REAL_METHODS);
Sut sut = new Sut(bar);
sut.doSomething();
bar.verify(...);
}
If Bar
is a class, not an interface, then you can use doCallRealMethod()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With