简体   繁体   中英

Testing steps of DAO layer and Service layer of Spring MVC and Hibernate using Junit

Pardon me if it is a stupid question.I'm trying to learn Spring MVC,Hibernate,Junit by doing a project. I'm using MySQL database. Problem is I'm not understanding how to test DAO layer or Service layer of my project Junit.I've tested my model classes easily. I searched for DAO & Service layers, but the tutorials I saw,made me more confused. None of them actually match pattern of my project. I know in-memory used for testing process. Some testing configuration is also needed. Somewhere text-context,somewhere used java configuration class. Now, I actually want to know what steps I really have to do one by one to test this layers and it will be helpful if you can tell me what have to be done in each step. I've several DAO,Service,and Model classes. I've given one class from each layer. My servlet-context.xml file which is in WEB-INF:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

  <!-- Enable @Controller annotation support -->
  <mvc:annotation-driven />

  <!-- Map simple view name such as "test" into /WEB-INF/test.jsp -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/" />
    <property name="suffix" value=".jsp" />
  </bean>

  <!-- Scan classpath for annotations (eg: @Service, @Repository etc) -->
  <context:component-scan base-package="com.mahin"/>

  <!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
       username root and blank password. Change below if it's not the case -->
  <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/webchatapp"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
    <property name="validationQuery" value="SELECT 1"/>
  </bean>

  <!-- Hibernate Session Factory -->
  <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="packagesToScan">
      <array>
        <value>com.mahin.models</value>
      </array>
    </property>
    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.MySQLDialect
      </value>
    </property>

  </bean>

  <!-- Hibernate Transaction Manager -->
  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="mySessionFactory"/>
  </bean>

  <!-- Activates annotation based transaction management -->
  <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

One of my model class

package com.mahin.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="friends")
public class Friends {

  @Id @GeneratedValue
 private long friendid;
  private long reqsender;
  private long reqreceiver;
  private int rank;
  private boolean granted;
 public long getFriendid() {
    return friendid;
}
public void setFriendid(long friendid) {
    this.friendid = friendid;
}
public long getReqsender() {
    return reqsender;
}
public void setReqsender(long reqsender) {
    this.reqsender = reqsender;
}
public long getReqreceiver() {
    return reqreceiver;
}
public void setReqreceiver(long reqreceiver) {
    this.reqreceiver = reqreceiver;
}
public int getRank() {
    return rank;
}
public void setRank(int rank) {
    this.rank = rank;
}
public boolean getGranted() {
    return granted;
}
public void setGranted(boolean granted) {
    this.granted = granted;
}



}

One of my DAO class

package com.mahin.daos;

import java.util.List;

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

import com.mahin.models.Friends;

@Repository
public class FriendsDAOimpl implements FriendsDAO{

    @Autowired 
     private SessionFactory sessionFactory;

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

    @Override
    public void addFriend(Friends friend) {     
        getCurrentSession().save(friend);

    }

    @Override
    public void updateFriend(Friends friend) {

         Friends friendToUpdate = getFriend(friend.getFriendid());
         friendToUpdate.setGranted(friend.getGranted());
         friendToUpdate.setRank(friend.getRank());
         friendToUpdate.setReqreceiver(friend.getReqreceiver());
         friendToUpdate.setReqsender(friend.getReqsender());

            getCurrentSession().update(friendToUpdate);

    }

    @Override
    public Friends getFriend(long friendid) {

        Friends friend = (Friends) getCurrentSession().get(Friends.class, friendid);
        return friend;
    }

    @Override
    public void deleteFriend(long friendid) {

        Friends friend = getFriend(friendid);
        if (friend != null)
            getCurrentSession().delete(friend);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Friends> getFriends() {

        return getCurrentSession().createQuery("from friends").list();
    }

}

And finally one of my Service class

package com.mahin.services;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mahin.daos.FriendsDAO;
import com.mahin.models.Friends;

@Service
@Transactional
public class FriendsServiceimpl implements FriendsService{

    @Autowired 
     private FriendsDAO friendsDAO;

    @Override
    public void addFriend(Friends friend) {     
        friendsDAO.addFriend(friend);
    }

    @Override
    public void updateFriend(Friends friend) {
        friendsDAO.updateFriend(friend);
    }

    @Override
    public Friends getFriend(long friendid) {
        return friendsDAO.getFriend(friendid);
    }

    @Override
    public void deleteFriend(long friendid) {
        friendsDAO.deleteFriend(friendid);
    }
    @Override
    public List<Friends> getFriends() {
        return friendsDAO.getFriends();
        }

}

You have two options:

  • Unit Testing: Test if the method works as expected in isolation. This is the solely purpose of JUnit. For unit testing, you must not connect to external resources like a database. This is, you have to mock your data source provider and any other component that is external to the class you're testing. You can mock methods and classes using a mock framework like PowerMock, EasyMock or Mockito.

  • Integration Testing: Test if the method works as expected in an integrated environment. Here you test if the class can interact with other external resources like database connection, and perform its functionality integrated with these components.

For Spring projects, there is Spring Test framework which provides additional functionalities to JUnit test classes to do Unit or Integration Testing. Here's a basic example to perform integration test on your posted Dao class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("path/to/your/spring-config.xml")
public class MyTest {

    @Autowired
    FriendsDAO friendsDao;

    @Test
    public void testAddFriend() {
        final int rank = 1;
        Friends friend = new Friends();
        friend.setRank(rank);
        friendsDao.addFriend(friend);
        final long friendId = friend.getId();
        Friends insertedFriend = friendsDao.getFriend(friendId);
        Assert.assertEquals(insertedFriend.getRank(), friend.getRank());
        //assert if all necessary fields are equal
        //or assert if both are equals in case your Friends class implements equals method
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM