Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

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: 13505
305
  • 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: 22584
122
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:
     
    WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
    Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    reply
      Bookmark Topic Watch Topic
    • New Topic