Mocking an interface with Mockito

We Are Going To Discuss About Mocking an interface with Mockito. So lets Start this Java Article.

Mocking an interface with Mockito

Advertisements
  1. Mocking an interface with Mockito

    @InjectMocks will not instantiate or mock your class. This annotation is used for injecting mocks into this field.
    If you want to test serviceImpl you will need to mock in this way:

  2. Mocking an interface with Mockito

    @InjectMocks will not instantiate or mock your class. This annotation is used for injecting mocks into this field.
    If you want to test serviceImpl you will need to mock in this way:

Solution 1

Advertisements

@InjectMocks will not instantiate or mock your class. This annotation is used for injecting mocks into this field.

If you want to test serviceImpl you will need to mock in this way:

@Mock
private OrderIF order;

@InjectMocks
private Service reqService = new ServiceImpl(); 

To make it work you either need to use runner or MockitoAnnotations.initMocks(this); in @Before method.

Original Author Sergii Bishyr Of This Content

Solution 2

Advertisements

I’m guessing that order is null and you’re getting the NullPointerException here:

when(order.ordersFor(type)).thenReturn(ll);

For @InjectMocks to work and instantiate your class, you’ll need to add a runner:

@RunWith(MockitoJUnitRunner.class)
public class ServiceImplTest {
    // ...
}

You don’t have to use the runner, refer to the documentation for alternatives.

Original Author Jonathan Of This Content

Conclusion

Advertisements

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Advertisements
Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment