Abhijeet Panwar
Abhijeet Panwar

Reputation: 1857

How to mock Abstract class method?

I need to test a class that extends an abstract class and uses it protected method. Here is the code:

public class DataDaoImpl extends SuperDao<CustomClass> 
{
   public List<Long> findAllbyId(Long productId)
   {
      Session session = getCurrentSession();
      .......
      //Rest of code
   }
}

and here is the code of abstract class:

public abstract class SuperDao<T>
{
    protected final Session getCurrentSession() 
     {  
       return sessionFactory.getCurrentSession();
     }
}

Now how should I write unit test for DataDaoImpl and should mock session in Session session = getCurrentSession();?

I have tried different solutions on Stackoverflow but I am still not able to mock it and get session mock.

I have tried using mocking getcurrentSession() as suggested in answer with following code:

@Test
public void testDataDaoImpl()
{
SessionFactory mockedSessionFactory = Mockito.mock(SessionFactory.class);
Session mockedSession = Mockito.mock(Session.class); 
Mockito.when(mockedSessionFactory.getCurrentSession()).thenReturn(mockedSession);   
DataDaoImpl DDI_Instance = new DataDaoImpl((long) 120);
DDI_Instance.findAllbyId(Long productId);
}

But still session.getCurrentSession() fails.

Upvotes: 0

Views: 2161

Answers (1)

www.hybriscx.com
www.hybriscx.com

Reputation: 1129

As DataDaoImpl extends SuperDao, method getCurrentSession inherently becomes a part of DataDaoImpl and you should avoid mocking the class being tested.

What you need to do is, mock SessionFactory and return mocked object when sessionFactory.getCurrentSession() is called. With that getCurrentSession in DataDaoImpl will return the mocked object.

Hope it helps.

Upvotes: 2

Related Questions