Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Testing DAO with Mockito

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
I am new to Mockito and trying to write a test for my demo project. I have a project, using Spring 5 and Hibernate. I have a DAO class which use Hibernate session and query.

@Repository
@Transactional
public class CustomerDaoImpl implements CustomerDao {

@Autowired
   private SessionFactory sessionFactory;

@Override
public Customer getCustomerById(int id) {
Session session = null;
Customer customer = null;

try{
session = sessionFactory.openSession();
customer = session.find(Customer.class, id);
}catch(Exception e) {
throw (e);
}finally {
session.close();
}
return customer;
}
}

// Test Class
@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@ContextConfiguration(locations = "classpath:spring-hibernate-config-test.xml")
public class CustomerDaoTest {

@InjectMocks
private CustomerDaoImpl customerDao;

@Mock
SessionFactory sessionFactory;

Customer customer;

@Before
public void setupMock(){
    MockitoAnnotations.initMocks(this);
    sessionFactory = mock(SessionFactory.class);
    customerDao.setSessionFactory(sessionFactory);
}

@Test
@Transactional
@Rollback(true)
@DisplayName("DAO: Find customer by given id")
public void testGetCustomerById() {
int customerId = 14;
Customer customer = new Customer(14, "Mike");
when(sessionFactory.openSession().find(Customer.class, customerId)).thenReturn(customer);

assertNotNull(customer);
    assertEquals(customerId, customer.getIfCustomerId());
}
}

Error:
java.lang.NullPointerException
at com.primis.dao.CustomerDaoTest.testGetCustomerById(CustomerDaoTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)

For some reason my session is null. Please can someone advice where I am going wrong.

Thank you
 
Saloon Keeper
Posts: 13825
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is your session null or your session factory?
 
Sheriff
Posts: 22644
123
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ish Fad wrote:


With Mockito, every method of a mocked object does the following:
  • If the return type is void, it does nothing
  • If the return type is a primitive, it returns the default value for that type (false, 0, etc)
  • If the return type is a collection or map, it returns an empty instance (or null, I can't remember)
  • Otherwise it returns null

  • To override this behaviour, you need to setup the return values.  You try to do that; however, you use a chained call. Since you didn't specify what sessionFactory.openSession() should return, it returns null. If you then call find on it, an NPE is thrown.

    In this case, you'll have to do nested mocking. Create a mock for the Session; either as a field annotated with @Mock, or programmatically using mock(Session.class). Then setup the mocking:
     
    They gave me pumpkin ice cream. It was not pumpkin pie ice cream. Wiping my tongue on this tiny ad:
    Free, earth friendly heat - from the CodeRanch trailboss
    https://www.kickstarter.com/projects/paulwheaton/free-heat
    reply
      Bookmark Topic Watch Topic
    • New Topic