-2

Mockito.mock and @Mock are supposed to do the same thing. Curiously enough, this does not seem to be the case when mocking UriInfo. In my unit test using JUnit4, the code below works:

private UriInfo uriInfo = Mockito.mock(UriInfo.class);

whereas this raised error of "parameter uriInfo not set" upon running the test:

@Mock
private UriInfo uriInfo;
Treefish Zhang
  • 1,131
  • 1
  • 15
  • 27
  • if you are using `@Mock` , you need to initialize mocks using `MockitoAnnotations.initMocks(this)` Do you have this? – pvpkiran Nov 21 '17 at 19:58
  • If you are using Mockito mocking annotations, you need to call `MockitoAnnotations.initMocks(this);` This is often done in a method that is marked with the @Before annotation. – DwB Nov 21 '17 at 19:58
  • From your link `Note that to enable Mockito annotations during test executions, the MockitoAnnotations.initMocks(this) static method has to be called.` – Oleg Nov 21 '17 at 19:59
  • That is wild! I do have that @RunWith statement. – Treefish Zhang Nov 21 '17 at 20:13

1 Answers1

2

Have you done mock initialization?

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
}

Or you can use a special runner on your test class:

@RunWith(MockitoJUnitRunner.class)

Where do you use your mocked urlInfo? Did you specify a mocked implementation for it's methods? For example,

when(urlInfo.getPath()).thenReturn("some/path");
when(urlInfo.toString()).thenReturn("some/path"); 
kotslon
  • 147
  • 10
  • Yes, I did use `@RunWith(MockitoJUnitRunner.class)` to have mockito run the test. – Treefish Zhang Nov 21 '17 at 20:11
  • uriInfo is passed as an object, with no method invoked. The class under test does `extends` another class. But my question here is why @Mock differs from its alternative. It almost appears that @Mock returned null, whereas Mockito.mock() returned a non-null value. – Treefish Zhang Nov 21 '17 at 21:35
  • are you sure that it differs? can you see `null` in debugger after initialization? – kotslon Nov 21 '17 at 21:37
  • I am certain of the `null` because in the Failure Trace I can see the message unique for the Exception thrown when uriInfo is null (inside the parent class which my class extends). – Treefish Zhang Nov 21 '17 at 21:58
  • @TreefishZhang maybe it's not the `urlInfo` itself is null. Check it. Maybe one of it's methods is used - and **all** methods of a mock return `null` by default. – kotslon Nov 21 '17 at 22:01