Mockito测试服务层

时间:2016-07-02 10:33:30

标签: spring-mvc mockito

我是Mockito的新手并尝试测试我的服务层。我的DAO层在服务中是@Autowired,Hibernate也是自动装配的。测试时没有加载Hibernate。我总是得到NullPointerException。这是我的代码:

EmployeeService(界面)

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 (界面)

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 (测试类)

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() {

}

}

我在互联网上找不到这个。

2 个答案:

答案 0 :(得分:4)

仅仅因为您在测试中创建了一个模拟员工DAO并不意味着您的服务将使用它。它不会。当你这样做

new EmployeeServiceImpl();

您创建了服务的实例,并且其DAO字段未初始化(因此为null)。

使用构造函数注入,并将模拟DAO传递给服务构造函数:

public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeDAO dao;

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

    ...
}

和/或至少正确使用Mockito注释:

@Mock
private EmployeeDAO employeeDAO;

@InjectMocks
private EmployeeServiceImpl employeeService;

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

答案 1 :(得分:0)

好的,我找到了一些修复程序,现在测试运行了。

首先,我修复了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();
   }
}

这是EmployeeServiceTest类

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() {

}

}