Reputation: 9411
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)
Upvotes: 0
Views: 153
Reputation: 2149
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;
Upvotes: 2
Reputation: 16039
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()
.
Upvotes: 1