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
  • 4,965
  • 2
  • 26
  • 37
onkami
  • 7,608
  • 16
  • 72
  • 156

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
  • 1,865
  • 14
  • 29
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,064
  • 6
  • 51
  • 88