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); } }
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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With