0

I have a JUnit test that reads

public class  EventHandlerTest  {

    @Mock
    ThreadPoolExtendedExecutor threadPoolExtendedExecutor;

    private EventHandler handler;
    private Map<Queue<SenderTask>> subBuffers = new HashMap<>();


    @Before
    public void setUp() {
        // PROBLEM: threadPoolExtendedExecutor null!
        handler = new EventHandler(subBuffers, threadPoolExtendedExecutor);
    }


}

When I call new in setUp, I have threadPoolExtendedExecutor=null. I would like to insert some mocked threadPoolExtendedExecutor so, I do not have NullPointer problems when calling its methods (so simple interface mock is enough for me at this moment)

Red Boy
  • 5,429
  • 3
  • 28
  • 41
onkami
  • 8,791
  • 17
  • 90
  • 176

2 Answers2

2

You can simply mock it using (in setUp)

threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class);

@Before
public void setUp() {
    threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class);
    handler = new EventHandler(subBuffers, threadPoolExtendedExecutor);
}

You can also let MockitoJUnitRunner do it for you : don't forget to inject mocks in your service under test by annotating it with @InjectMocks

@RunWith(MockitoJUnitRunner.class)
public class  EventHandlerTest  {

    @Mock
    ThreadPoolExtendedExecutor threadPoolExtendedExecutor;
Lho Ben
  • 2,053
  • 18
  • 35
1

If you would like to use the @Mock or @InjectMocks annotations on the test class fields then you need to add @RunWith(MockitoJUnitRunner.class) at the class level.

@RunWith(MockitoJUnitRunner.class)
public class  EventHandlerTest  {

    @Mock
    ThreadPoolExtendedExecutor threadPoolExtendedExecutor;

Another approach is to not use the above annotations and manually create mocks by calling org.mockito.Mockito.mock().

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92