Bhanuprasad
Bhanuprasad

Reputation: 229

How to work with EasyMock for testing servicelayer in SpringMVC?

I am working on Hibernate and Spring MVC application,But I want to test my ServiceLayer by using Easy Mock ,I am doing that but I am not understanding this is correct way or not.Please check my code below and give me suggestions

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("[email protected]");
  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);

 }

}

For More Information I am Writing my DaoImpl also 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;
}

}

In My database I have record with [email protected] & above password , But I am not getting that record when I am exectue my testcase .please tell me if I doing any thing wrong and is this the correct way to write easy mock,If it is wrong Please tell me how to write testcase by using easy mock .Any one help me.

Upvotes: 1

Views: 2252

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

What you have is perfectly normal. But I think you haven't really understood what a mock is. A mock is a "false" implementation of a class or interface that does nothing, except what you tell it to do. The whole point of mocking DAOs when testing services is to be able to test the service logic without actually needing a functional DAO, a database populated with test data, etc.

So when you're saying

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

you're creating a service that uses such a "false" DAO.

By default, all the DAO methods won't do anything except return null or a default value.

When you do

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

and replay the mock, then every time the DAO's login() method is called with this student as argument, it will return a new StudentEntity. And obviously, this new StudentEntity has a null email, since the constructor of StudentEntity leaves the email as null. What you have in your database is thus completely irrelevant.

Note that such a test doesn't need any Spring context to run. It doesn't need to be annotated with

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

since you're not using Spring at all. That's why dependency injection is so useful: it allows unit-testing your code without needing any dependency, any framework or anything.

Upvotes: 1

Related Questions