如何使用EasyMock测试Spring MVC中的服务层?

时间:2014-08-17 19:41:35

标签: spring-mvc easymock

我正在开发 Hibernate Spring MVC 应用程序,但我想使用 Easy Mock 测试我的ServiceLayer,我这样做但我不明白这是否正确。请检查下面的代码并给我建议

StudentDao

package com.bhanu.dao;
import com.bhanu.entity.StudentEntity;
import com.bhanu.modelpojo.Student;
public interface StudentDao {
public StudentEntity login(Student student);
public StudentEntity findUser(String email);

} 的 StudentService

package com.bhanu.service;
import com.bhanu.entity.StudentEntity;
import com.bhanu.modelpojo.Student;
public interface StudentService{
public StudentEntity login(Student student);
public StudentEntity findUser(String email);

}

StudentServiceImpl

@Service
public class StudentServiceImpl implements StudentService {

@Autowired
private BaseDao baseDao;
@Autowired
private JavaMailSender mailSender;
@Autowired
private StudentDao studentDao;
public StudentServiceImpl() {
    super();
    // TODO Auto-generated constructor stub
}

@Override
public StudentEntity login(Student student) {
StudentEntity studentEntity = studentDao.login(student);
    return studentEntity;
}

public BaseDao getBaseDao() {
    return baseDao;
}
public void setBaseDao(BaseDao baseDao) {
    this.baseDao = baseDao;
}
public JavaMailSender getMailSender() {
    return mailSender;
}
public void setMailSender(JavaMailSender mailSender) {
    this.mailSender = mailSender;
}
public StudentDao getStudentDao() {
    return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
    this.studentDao = studentDao;
}

}

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.bhanu" />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/student" />
    <property name="username" value="root" />
    <property name="password" value="root" />
</bean>
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.bhanu.entity" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.format_sql">false</prop>
            <prop key="hibernate.cache.use_second_level_cache">false</prop>
            <prop key="hibernate.cache.use_query_cache">false</prop>
        </props>
    </property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

对MyTestCase

package com.bhanu.servicesimpl;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:mvc-dispatcher-servlet.xml")
 public class MyTestCase {
 private StudentServiceImpl studentServiceImpl;
 private StudentDao studentDao;
 private BaseDao baseDao;
 private JavaMailSender javaMailSender;
//execute before test
  @Before
  public void before() {
    studentDao =EasyMock.createStrictMock(StudentDao.class);
    baseDao =EasyMock.createStrictMock(BaseDao.class);
    javaMailSender =EasyMock.createStrictMock(JavaMailSender.class);
    studentServiceImpl = new StudentServiceImpl();
    studentServiceImpl.setBaseDao(baseDao);
    studentServiceImpl.setMailSender(javaMailSender);
    studentServiceImpl.setStudentDao(studentDao);
    System.out.println("in before");
  }
   //test case
  @Test
 public void test() {
  System.out.println("in test");
  Student student = new Student();
  student.setEmail("hari@gmail.com");
  student.setPassword("12530");
  EasyMock.expect(studentDao.login(student))
  .andReturn(new StudentEntity());
          EasyMock.replay(studentDao);

          StudentEntity   studentEntity1 =studentServiceImpl.login(student);
          System.out.println(studentEntity1 .getEmailId());***//I got Null Value***
          assertNotNull(studentEntity1);
          EasyMock.verify(studentDao);

 }

}

更多信息我也在写我的DaoImpl 的 StudentDaoImpl

@SuppressWarnings("unchecked")
@Repository

public class StudentDaoImpl implements StudentDao {

@Autowired
private HibernateTemplate hibernateTemplate;

@Override
public StudentEntity findUser(String email) {
    StudentEntity myStudentObject = null;

    StudentEntity studentEntity = new StudentEntity();
    studentEntity.setEmail(email);

    List<StudentEntity> studentList = hibernateTemplate.findByExample(
            studentEntity.getClass().getName(), studentEntity);
    if (studentList != null && studentList.isEmpty() && studentList.size()!=0) {
        myStudentObject = DataAccessUtils.requiredUniqueResult(studentList);

    }
    return myStudentObject;
}

}

在我的数据库中,我记录了hari@gmail.com&amp;以上密码,但是当我执行我的测试用例时,我没有得到那条记录。请告诉我,如果我做了任何错误,这是正确的方法来编写简单的模拟,如果是错的请告诉我如何编写测试用例很容易模拟。任何人帮助我。

1 个答案:

答案 0 :(得分:1)

你拥有的是完全正常的。但我认为你还没有真正明白模拟是什么。模拟是&#34;虚假&#34;实现没有任何作用的类或接口,除了你告诉它做的事情。在测试服务时模拟DAO的重点是能够测试服务逻辑而不需要实际需要功能DAO,填充测试数据的数据库等。

所以当你说

studentDao =EasyMock.createStrictMock(StudentDao.class);
studentServiceImpl = new StudentServiceImpl();
studentServiceImpl.setStudentDao(studentDao);

您正在创建使用此类&#34; false&#34; DAO。

默认情况下,除了返回null或默认值之外,所有DAO方法都不会执行任何操作。

当你这样做时

EasyMock.expect(studentDao.login(student)).andReturn(new StudentEntity());

并重播模拟,然后每次使用此学生作为参数调用DAO的login()方法时,它将返回一个新的StudentEntity。很明显,这个新的StudentEntity有一个空电子邮件,因为StudentEntity的构造函数将电子邮件保留为null。因此,您在数据库中拥有的内容完全无关紧要。

请注意,此类测试不需要运行任何Spring上下文。它不需要用

注释
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:mvc-dispatcher-servlet.xml")

因为你根本不使用Spring。这就是依赖注入如此有用的原因:它允许对代码进行单元测试,而不需要任何依赖,任何框架或任何东西。