Ria Sachdeva
Ria Sachdeva

Reputation: 113

Unable to stub-out the dependency using mockito

I have a simple test case where I want to mock out the object. However, for some reason I am getting Null Pointer exception as orderDaoImpl is not mocked out.

I am new to mockito any help in this regard is appreciated.

public class OrderBusinessImplTest extends TestCase {

    //Stub-out the dependency
    @Mock
    OrderDAOImp orderDao;

    @Before
    public void setup()
    {
        //We need this because at runtime it will scan all the references of OrderDao and mock the object
        System.out.println("Hey");
        MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void testPlaceOrder() throws SQLException, BOException {
        OrderBusinessImpl orderBusiness=new OrderBusinessImpl();
        orderBusiness.setDao(orderDao);
        //When is an important method which is used to mock out the object call
        Order order= new Order();
        //Set the expectations
        when(orderDao.createOrder(order)).thenReturn(new Integer(1));
        boolean results=orderBusiness.placeOrder(order);

        //Verify the results
        assertTrue(results);
        verify(orderDao.createOrder(order));
    }
}


Result:

java.lang.NullPointerException at OrderBO.OrderBusinessImplTest.testPlaceOrder(OrderBusinessImplTest.java:40)

After debugging I found out that orderDao is null and when I am trying to call this orderDao.createOrder(order) it leads to an exception.

Upvotes: 0

Views: 42

Answers (1)

pirho
pirho

Reputation: 12215

For some reason extending TestCase makes JUnit not run @Before method. You might have noticed that because you also have this log line there:

System.out.println("Hey");

If you really want to extend TestCase you need to move MockitoAnnotations.initMocks(this); (preferably as the first line) in your test method testPlaceOrder and get rid of your @Before method.

But even better alternative would be to add annotation:

@RunWith(MockitoJUnitRunner.class)

to your test class OrderBusinessImplTest (and remove @Before method) because then you would get mocks inited automatically (so without any initMocks(this)).

In any case think if you really need to extend TestCase?

Also your last verify should be like:

verify(orderDao).createOrder(order);

Upvotes: 2

Related Questions