Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking an interface with Mockito

Tags:

java

mockito

Can someone please help me with the below Mock object. I want to write a mock test case for ServiceImpl class. I want to mock OrderIF interface:

public interface OrderIF{     List<Order> ordersFor(String type); } 

The implementation of service is:

public class ServiceImpl implements Service {     private List <Order> orders ;     private OrderIF orderif ; // this is 3rd party interface      public int getval(String type) {        //some code          // this returns a list of objects (orders)        orders = orderif.ordersFor(type);         // some code         return orders.get(0)     } } 

My code give NullPoinerException:

public class ServiceImplTest {      private List <Order> ll ;      private service reqService ;        @InjectMocks      private orderIF order;       @Before      public void setUp() throws Exception {          ll = new ArrayList<Order> ();          ll.add(new Order("Buy"  ,  11 , "USD" ));          ll.add(new Order("Sell" ,  22 , "USD" ));          reqService = spy(new ServiceImpl());      }       @Test      public void test() {         String type= "USD" ;          when(order.ordersFor(type)).thenReturn(ll);         q = reqService.getval(type);         assertTrue(q.get().ask == 232.75);     } } 
like image 365
Mike Avatar asked Apr 22 '16 00:04

Mike


People also ask

Can we mock an interface using Mockito?

We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object.

How do you inject an mock for an interface?

Here is what works: public class TestDo { @Mock private Do do; @Mock private ABC abc; @Before public void init() { MockitoAnnotations. initMocks(this); do. abc = abc; } @Test public void testDo() { when(do.


1 Answers

@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.

like image 185
Sergii Bishyr Avatar answered Sep 25 '22 01:09

Sergii Bishyr