0

I'm new to Mockito and trying to test my service layer. My DAO layer is @Autowired in service and Hibernate is also autowired. Hibernate is not loading while testing. I always get NullPointerException. Here is my code:

EmployeeService (Interface)

package com.spring.crud.service;

import java.util.List;

import com.spring.crud.entity.Employee;

public interface EmployeeService {

    Employee save(Employee employee);

    boolean update(Employee employee);

    Employee find(Integer id);

    List<Employee> getEmployees();

    boolean remove(Integer id);
}

EmployeeServiceImpl (Class)

package com.spring.crud.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spring.crud.dao.EmployeeDAO;
import com.spring.crud.entity.Employee;

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
private EmployeeDAO dao;

public Employee save(Employee employee) {

    return dao.save(employee);
}

public boolean update(Employee employee) {

    return dao.update(employee);
}

public Employee find(Integer id) {

    return dao.find(id);
}

public List<Employee> getEmployees() {

    return dao.getEmployees();
}

public boolean remove(Integer id) {

    return dao.remove(id);
}
}

EmployeeDAO (Interface)

package com.spring.crud.dao;

import java.util.List;

import com.spring.crud.entity.Employee;

public interface EmployeeDAO {

Employee save(Employee employee);

boolean update(Employee employee);

Employee find(Integer id);

List<Employee> getEmployees();

boolean remove(Integer id);
}

EmployeeDAOImpl (Class)

package com.spring.crud.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.spring.crud.entity.Employee;

@Transactional
@Repository
public class EmployeeDAOImpl extends HibernateUtil implements EmployeeDAO{

public Employee save(Employee employee) {

    Session session = getCurrentSession();

    session.save(employee);

    return employee;
}

public boolean update(Employee employee) {

    Session session = getCurrentSession();

    session.update(employee);

    return false;
}

public Employee find(Integer id) {

    Session session = getCurrentSession();

    Employee employee = (Employee)session.get(Employee.class, id);  

    return employee;
}

public List<Employee> getEmployees() {

    Session session = getCurrentSession();

    Query query = session.createQuery("from Employee");

    @SuppressWarnings("unchecked")
    List<Employee> employees = (List<Employee>)query.list();

    return employees;
}

public boolean remove(Integer id) {

    Session session = getCurrentSession();

    Employee employee = (Employee)session.get(Employee.class, id);  

    if(employee!=null){

        session.delete(employee);

        return true;
    }

    return false;
}
}

HibernateUtil

package com.spring.crud.dao;

import javax.annotation.PostConstruct;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibernateUtil extends HibernateDaoSupport{

@Autowired
private SessionFactory sessionFactory;

@PostConstruct
public void init() {
    setSessionFactory(sessionFactory);
}   

public Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
}
}

EmployeeServiceTest (Test class)

package com.spring.crud.test;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.test.context.ContextConfiguration;

import com.spring.crud.config.WebConfig;
import com.spring.crud.dao.EmployeeDAO;
import com.spring.crud.dao.EmployeeDAOImpl;
import com.spring.crud.entity.Employee;
import com.spring.crud.service.EmployeeService;
import com.spring.crud.service.EmployeeServiceImpl;

@ContextConfiguration(classes = {WebConfig.class})
public class EmployeeServiceTest {

private EmployeeDAO employeeDAO;

private EmployeeService employeeService = new EmployeeServiceImpl();

@Spy
List<Employee> employees = new ArrayList<Employee>();

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);

    employeeDAO = mock(EmployeeDAOImpl.class);
}

@Test
public void listEmployees() {

}

@Test
public void create() {

    Employee employee = new Employee();

    employee.setDateOfBirth(new Date());
    employee.setGender("male");
    employee.setName("Ashutosh");

    when(employeeDAO.save(any(Employee.class)))
        .thenAnswer(new Answer<Employee>() {

            public Employee answer(InvocationOnMock invocation) throws Throwable {

                Employee employee = (Employee) invocation.getArguments()[0];

                employee.setId(1);

                return employee;
            }

        });

    assertNull(employee.getId());

    employee = employeeService.save(employee);

    assertNotNull(employee.getId());

    assertTrue(employee.getId()>0);
}

@Test
public void edit() {

}

@Test
public void update() {

}

@Test
public void remove() {

}

}

I can't find much on this on the internet.

2
  • Since a working answer came in from JB Nizet, I have rolled back the changes made subsequently. Please do not modify your questions in such a way that invalidates existing answers. Thanks. Commented Feb 19, 2017 at 10:57
  • May I suggest that JB Nizet's answer is accepted? To accept an answer, click on the tick mark adjacent, so that it turns green. Commented Feb 19, 2017 at 10:58

2 Answers 2

6

Just because you create a mock employee DAO in your test doesn't mean that your service will use it. It won't. When you do

new EmployeeServiceImpl();

you create an instance of the service, and its DAO field is left uninitialized (so null).

Use constructor injection, and pass the mock DAO to the service constructor:

public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeDAO dao;

    @Autowired
    public EmployeeServiceImpl(EmployeeDAO dao) {
        this.dao = dao;
    }

    ...
}

And/or at least use Mockito annotations correctly:

@Mock
private EmployeeDAO employeeDAO;

@InjectMocks
private EmployeeServiceImpl employeeService;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi JB, made the suggested changes, but still getting "employee" object as null after saving, thanks
I downloaded your project, fixed its layout, removed the non-compiling DataSource initialization, copy-pasted the code of the test in your question, added the missing import for Mock, ran the test, and it passed. So you're probably not executing the code that is in your question. And now that you edited it, my answer looks all weird, because it answered your initial question.
oops, don't feel bad, just wanted to complete the code. I added a reference about your answer in the question. Since, this is my first mockito test, I probably missed out something. Can you please provide the code you fixed on your end? thanks
0

OK, I found some fixes and now the test runs.

First, I fixed the HibernateUtil

package com.spring.crud.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class HibernateUtil{

   @Autowired
   private SessionFactory sessionFactory;

   public Session getCurrentSession() {
      return sessionFactory.getCurrentSession();
   }
}

This is the EmployeeServiceTest class

package com.spring.crud.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

import java.util.Date;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.test.context.ContextConfiguration;

import com.spring.crud.config.WebConfig;
import com.spring.crud.dao.EmployeeDAO;
import com.spring.crud.entity.Employee;
import com.spring.crud.service.EmployeeServiceImpl;

@ContextConfiguration(classes = {WebConfig.class})
public class EmployeeServiceTest {

@Mock
private EmployeeDAO employeeDAO;

@InjectMocks
private EmployeeServiceImpl employeeService;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void listEmployees() {

}

@Test
public void create() {

    Employee employee = new Employee();

    employee.setDateOfBirth(new Date());
    employee.setGender("male");
    employee.setName("Ashutosh");

    when(employeeDAO.save(any(Employee.class)))
        .thenAnswer(new Answer<Employee>() {

            public Employee answer(InvocationOnMock invocation) throws Throwable {

                Employee employee = (Employee) invocation.getArguments()[0];

                employee.setId(10);

                return employee;
            }

        });

    assertNull(employee.getId());

    employee = employeeService.save(employee);

    System.out.println("Id = " + employee.getId());

    assertNotNull(employee);

    assertEquals((Integer)10, (Integer)employee.getId());
}

@Test
public void edit() {

}

@Test
public void update() {

}

@Test
public void remove() {

}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.