0

No matter what I've tried, test end up on NullPointerException on stubbing statement. Method to test:

public boolean selectEntity(final List<T> entities) {
if (entities.contains(helper.getLastEntity())) {
    return true;
 }
}

Above snippet is enough, cause (in unit test) cannot even enter into conditional statement. To clarify: getLastEntity returns field

private T lastEntity 

for object of class Helper. T is an interface.

My best try is:

private @Mock Helper helper;
private @Mock List<T> entities;
...
@Test
public void testSelectEntity(){
    when(entities.contains(notNull(T.class))).thenReturn(true);
    when(helper.getLastEntity()).thenReturn((T) anyObject());
}

How to proceed here?

UPDATE: follow your suggestions, I rewrote test (mocks are for sure initialized this time:))

final DummyT dummyT = new DummyT();
when(helper.getLastEntity()).thenReturn(dummyT);
when(entities.contains(dummyT).thenReturn(true);

assertTrue(objectUnderTest.selectEntity(entities));

where DummyT implements T. Got null pointer on method execution, pointing on if statement.

oundru87
  • 43
  • 1
  • 8
  • Is this the only test that doesn't work? – dimoniy Feb 12 '14 at 16:09
  • Have you injected the mocks? – aNish Feb 12 '14 at 16:17
  • That's not what `anyObject()` is for. You'll actually have to create the object that you want to have returned. You are making the same error as the OP on http://stackoverflow.com/questions/21532988/stubbing-two-methods-in-a-mock-is-throwing-exception-using-mockito-and-spring-mo – Dawood ibn Kareem Feb 12 '14 at 17:29
  • Thanks for comments. I initialized mocks correctly this time, but got null pointer on execution stage (see question update). No idea what else could be wrong here.. Maybe mock of the list should be prepared in other way (I had never done this before)? – oundru87 Feb 13 '14 at 10:32

1 Answers1

2

At least two problems:

  • You cannot return an instance of the matcher anyObject(). Instantiate an object to return instead.
  • Depending on your mocking framework, you'll need to initialise mocking first. For example, in Mockito, use: MockitoAnnotations.initMocks(this);
alexvinall
  • 417
  • 4
  • 14