0

I'm trying to get familiar with Mockito Captor but I get both NullPointerException and InvalidUseOfMatchersException. I have a feeling, that I am doing something wrong and/or understanding the captor technique incorrectly.

Here is my testing class:

@Test
public void testFindByClientIdAndBatchDateBetween() {

    DateTime todayDateTime = new DateTime().withTimeAtStartOfDay();

    mockedTransactRepViewModel.capture().setClientId("123456");
    mockedTransactRepViewModel.capture().setBatchDate(todayDateTime.toDate());
    mockTransactRepViewRepository.save(mockedTransactRepViewModel.capture());

    verify(mockTransactRepViewRepository).findByClientIdAndClDateBetween("123456", todayDateTime.toDate(),
                                                                todayDateTime.plusDays(1).toDate()).get(0);

    String mockClientId = mockedTransactRepViewModel.getValue().getClientId();
    assertThat(mockClientId.equals("123456"));

    verify(mockTransactRepViewRepository, times(1)).save(mockedTransactRepViewModel.capture());
}

Edit: Complete stack trace:

java.lang.NullPointerException
    at domain.TransactRepViewRepositoryTest.testFindByClientIdAndBatchDateBetween(TransactRepViewRepositoryTest.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)


org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced argument matcher detected here:

-> at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
Deniss M.
  • 3,617
  • 17
  • 52
  • 100

1 Answers1

2

Captors don't quite work the way you have them. You should only call capture to stand in for an argument during a verify call, and then retrieve the captured value or values using getValue or getValues.

/* BAD */  mockedTransactRepViewModel.capture().setClientId("123456");

In a world without captors, if you need to check the value of a parameter that was received as part of an interaction with a mock, you would need to use Mockito matchers (eq or gt for example) or you would need to write a Hamcrest matcher to check what kind of value you receive.

/* in your system under test */
someSystem.setPowerLevel(9001);
someSystem.interact(new Widget(4));

/* in your test */
verify(mockSystem).setPowerLevel(gt(9000));  // greater than 9000
verify(mockSystem).interact(argThat(isAWidgetWithParameter(4)));

Naturally, this makes it hard to inspect multiple properties of an object, or to get a reference to an instance that you can pass elsewhere. That's where captors come in, either created through ArgumentCaptor.forClass or through the @Captor annotation.

/* in your system under test */
someSystem.interact(new Widget(4));

/* in your test */
verify(mockSystem).interact(widgetCaptor.capture());
Widget widgetInteractedWith = widgetCaptor.getValue();
assertEquals(4, widgetInteractedWith.getParameter());
doOtherAssertionsOn(widgetInteractedWith);

Behind the scenes, the capture method actually returns null, because you're never meant to interact with the return value of that method. Like other Mockito matchers, the call returns a dummy value, and Mockito sets some internal state so it knows to populate the Captor instead of trying to equality-match every argument. I wrote a longer answer on how Mockito matchers work, which explains more about this hidden stack.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • Hi, thanks for your answer, but I am having a bit of a hard time understanding it. I solved my problem in this way: `ArgumentCaptor transactRepViewModelArgumentCaptor = ArgumentCaptor.forClass(TransactRepViewModel.class); verify(mockTransactRepViewRepository, times(1)).save(transactRepViewModelArgumentCaptor.capture()); assertEquals("123456", transactRepViewModelArgumentCaptor.getValue().getClientId());` – Deniss M. Sep 14 '16 at 05:52
  • But I am not sure I am satisfied with this test. I think that I have to move to integration-testing, although my db admins are against it. – Deniss M. Sep 14 '16 at 05:54
  • 1
    @Deniss Your new test looks fine. The important part is that you only call `capture` from within `verify`'s method call, and then interact with the captured value using `getValue` afterwards. As for your test scope, that's up to you and your team to decide based on the general contract of your system under test. – Jeff Bowman Sep 14 '16 at 07:08