Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking consistency of multiple arguments using Mockito

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?

like image 777
Laurence Gonsalves Avatar asked Feb 04 '13 20:02

Laurence Gonsalves


2 Answers

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());
}
like image 115
Jeff Bowman Avatar answered Oct 15 '22 02:10

Jeff Bowman


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

like image 31
NamshubWriter Avatar answered Oct 15 '22 02:10

NamshubWriter