title: How to mock Hibernate Query.list() using Mockito
body: <p>This is my class which need to be tested:</p>
  
  <pre><code>@Repository
  @Transactional
  public class ProductDAOImpl implements ProductDAO {
  
  private static final Logger logger = Logger.getLogger(ProductDAOImpl.class);
  
  @Autowired
  private SessionFactory hibernateSessionFactory;
  
  
  @Override
  public ProductDTO getProduct(String isbn) throws ProductException {
      ProductDTO productDTO = new ProductDTO();
      Product product = getProductFromDb(isbn);
      BeanUtils.copyProperties(product, productDTO);
      return productDTO;
  }
  
  private Product getProductFromDb(String isbn) throws ProductException{
      Session session = this.hibernateSessionFactory.getCurrentSession();
  
  
      String hql = "FROM com.esp.dao.entity.Product P WHERE P.isbn13 = :isbn13";
      Query query = session.createQuery(hql);
      query.setParameter("isbn13",isbn);
  
  
      List&lt;Product&gt; productList = query.list();  // Want to mock this call
      if(productList.size() ==1)      
          return productList.get(0);
      else if(productList.size() &gt;1)
          // throw new ProductException("Cannot return product. Multiple products found.", HttpServletResponse.SC_NOT_FOUND);
          throw new ProductException("Cannot return product. Multiple products found.");
      else if(productList.size() == 0){
          throw new ProductException("Cannot return product. No products found.");
      }
      return null;
  
  }
  </code></pre>
  
  <p>I want to mock the <strong>query.list()</strong> method. This is what I have tried so far but getting exception: <strong>Type 'SessionFactory' is an interface and it cannot be spied on.</strong></p>
  
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  public class TestProductDaoImpl {
  
  @Spy
  private SessionFactory hibernateSessionFactory;
  @InjectMocks
  private ProductDAOImpl productDAOImpl;
  
  @Test
  public void testGetProduct() throws ProductException {
  
      Session session = this.hibernateSessionFactory.getCurrentSession();
  
      String hql = "";
      Query query = session.createQuery(hql);
      Query spy = Mockito.spy(query);
      List&lt;Product&gt; productList = getProductList();
      doReturn(productList).when(spy).list();
  
      productDAOImpl.getProduct("abc");
  
  
  }
  </code></pre>
  
  <p>I can mock the getProductFromDb(). But in that case there is no need to write a test case for that as the maximum part of the class is getting mocked.</p>