我们可以在JUnit测试用例中使用多个会话吗?

时间:2016-12-13 11:57:52

标签: java hibernate session junit

我一直在尝试为下面的类编写一个Junit测试用例。我能够成功运行一个测试用例。我正在使用session通过服务器从数据库中获取数据。 我试图将会话对象用作不同的实例。它适用于第一种方法,但不适用于任何其他方法。我知道我会犯一些愚蠢的错误。 这是我的班级:

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.hp.legacyloader.service.RetrievePublicationService;


@Controller
public class DashboardController {

    /*  private  RetrievePublicationService retrievePublicationService;

        @Autowired
        public DashboardController(RetrievePublicationService retrievePublicationService) {
            this.retrievePublicationService = retrievePublicationService;
        }*/

        @Autowired
         RetrievePublicationService retrievePublicationService;

    private static final Logger logger = Logger.getLogger(DashboardController.class);


    @RequestMapping(value = "/viewDashboard")
    public String getPaginationDataPage() {     

        logger.info("Log4j info is working");
        logger.warn("Log4j warn is working");       
        logger.debug("Log4j debug is working");
        logger.error("Log4j error is working");
        return "ViewDashboard";     
    }



    @RequestMapping(value = "/getPaginationData/{pageSize}/{page}")
    //public @ResponseBody List<Map<String, Object>> getPaginationData(@PathVariable String pageSize, @PathVariable String page) {
    public @ResponseBody String getPaginationData(@PathVariable String pageSize, @PathVariable String page) throws JsonGenerationException, JsonMappingException, IOException {
       // Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("pageSize======"+pageSize);
        System.out.println("page======"+page);
        String json = null;
        List<Object[]> list = retrievePublicationService.listJob();

        List<Map<String, Object>> activeTeamMap = new ArrayList<Map<String,Object>>();

        if (list != null) {

            for (Object[] obj : list) {
                Map<String, Object> dropDownData = new HashMap<String, Object>();
                 Gson gson = new Gson();




                //System.out.println("obj.getPUBLICATION_ID()====" + ((EventLog) obj).getEventLogPid());

                dropDownData.put("publicationId",obj[0]);
                dropDownData.put("documentId",obj[1]);
                dropDownData.put("documentType",obj[2]);
                dropDownData.put("languageCode",obj[3]);
                dropDownData.put("processStartDate",obj[4]);
                dropDownData.put("publicationType",obj[5]);
                activeTeamMap.add(dropDownData);
                System.out.println("activeTeamMap==vbnbvn=="+activeTeamMap);
                json = gson.toJson(activeTeamMap);  
            }

        } 
        else {

        }

        return json;
    }

    @RequestMapping(value = "/getSearchData/{fdate}/{tdate}", method = RequestMethod.GET)
    public @ResponseBody List<Map<String, Object>> getSearchData(@PathVariable String fdate,
            @PathVariable String tdate) {
        System.out.println("fdate============" + fdate);
        System.out.println("tdate============" + tdate);
        String frdate = fdate.substring(2, 4) + "/" + fdate.substring(0, 2) + "/" + fdate.substring(4, 8);

        String todate = tdate.substring(2, 4) + "/" + tdate.substring(0, 2) + "/" + tdate.substring(4, 8);
        String json = null;
        List<Object[]> list = retrievePublicationService.getsearchData(frdate, todate);

        List<Map<String, Object>> activeTeamMap = new ArrayList<Map<String, Object>>();

        if (list != null) {

            for (Object[] obj : list) {
                Map<String, Object> dropDownData = new HashMap<String, Object>();
                dropDownData.put("publicationId", obj[0]);
                dropDownData.put("documentId", obj[1]);
                dropDownData.put("documentType", obj[2]);
                dropDownData.put("languageCode", obj[3]);
                dropDownData.put("processStartDate", obj[4]);
                dropDownData.put("publicationType", obj[5]);
                activeTeamMap.add(dropDownData);
                System.out.println("activeTeamMap==vbnbvn==" + activeTeamMap);
            }

        } else {

        }

        return activeTeamMap;
    }

    @RequestMapping(value = "/getEventLogDetails/{eventId}", method = RequestMethod.GET)
    public @ResponseBody List<Map<String, Object>> getEventLogDetails(@PathVariable String eventId) {
        System.out.println("fdate============"+eventId);


        String json = null;
        List<Object[]> list = retrievePublicationService.getEventLogDetails(eventId);

        List<Map<String, Object>> activeTeamMap = new ArrayList<Map<String,Object>>();

        if (list != null) {

            for (Object[] obj : list) {
                Map<String, Object> dropDownData = new HashMap<String, Object>();
                dropDownData.put("eventDetailLogPid",obj[0]);
                dropDownData.put("documentId",obj[1]);
                dropDownData.put("docLoadStatus",obj[2]);
                dropDownData.put("processStartDate",obj[3]);
                activeTeamMap.add(dropDownData);


                System.out.println("activeTeamMap==vbnbvn=="+activeTeamMap);
            }

        } 
        else {

        /*Map<String, Object> dropDownData = new HashMap<String, Object>();
            dropDownData.put("status", "404");
            dropDownData.put("message", "Data not found");
            activeTeamMap.add(dropDownData);*/

        }

        return activeTeamMap;
    }       



}

FOllowing是我的JUnit:

package com.hp.legacyloader.controller;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.spi.ServiceRegistry;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.hp.legacyloader.controller.DashboardController;
import com.hp.legacyloader.dao.RetrievePublicationDAO;
import com.hp.legacyloader.dao.RetrievePublicationDAOImpl;
import com.hp.legacyloader.service.RetrievePublicationService;
import com.hp.legacyloader.service.RetrievePublicationServiceImpl;

public class DashboardControllerTest {
      DashboardController dashboardController=new DashboardController();
      RetrievePublicationDAOImpl retrievePublicationDAOImpl=new RetrievePublicationDAOImpl();
      RetrievePublicationDAO retrievePublicationDAO;

        private static ServiceRegistry serviceRegistry; 
      private static Configuration configuration;

      SessionFactory sessionFactory;
      Session session;
      RetrievePublicationService retrievePublicationService;
      @Before
      public void getConnection(){
      try{
          configuration = new Configuration().addResource("hibernate.cfg.xml").configure();
          sessionFactory=configuration.buildSessionFactory(new ServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
          }
     catch(Throwable ex){
           System.err.println("Failed to create sessionFactory object." + ex);
           throw new ExceptionInInitializerError(ex); 

          }
      session=sessionFactory.openSession();
      }
      @Test
      public void testGetPaginationDataPage() {
          assertEquals("ViewDashboard", dashboardController.getPaginationDataPage());

      }

      //------------------------------------------------//
      @Test
      public void testGetPaginationData() {
          System.out.println("testGetPaginationData>>>>>>>>>>>");

            /*  try{
                configuration = new Configuration().addResource("hibernate.cfg.xml").configure();
                sessionFactory=configuration.buildSessionFactory(new ServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
                }
           catch(Throwable ex){
                 System.err.println("Failed to create sessionFactory object." + ex);
                 throw new ExceptionInInitializerError(ex); 

                }*/

          System.out.println(session);
          Transaction tx=null;
         // System.out.println("this===");
//          RetrievePublicationService retrievePublicationService=Mockito.mock(RetrievePublicationService.class);    

      //    System.out.println("pageSize======"+pageSize);
      //    System.out.println("page======"+page);
            String json = null;
            try{
            tx=session.beginTransaction();
            List<Object[]> list= sessionFactory.openSession().createQuery("select publicationId,documentId,documentType,languageCode,processStartDate,eventType from EventLog").list();

            tx.commit();



        System.out.println(list.get(0));
        List<Map<String, Object>> activeTeamMap = new ArrayList<Map<String,Object>>();

            if (list != null) {

                  for (Object[] obj : list) {
                        System.out.println(list.get(1));
                        Map<String, Object> dropDownData = new HashMap<String, Object>();
                        Gson gson = new Gson();

                        dropDownData.put("publicationId",obj[0]);
                        dropDownData.put("documentId", obj[1]);
                        dropDownData.put("documentType", obj[2]);
                        dropDownData.put("languageCode", obj[3]);
                        dropDownData.put("processStartDate", obj[4]);
                        dropDownData.put("publicationType", obj[5]);
                        activeTeamMap.add(dropDownData);
                        System.out.println("activeTeamMap==vbnbvn=="+dropDownData.get(obj));
                        json = gson.toJson(activeTeamMap);  
                        System.out.println(json);
      }
            }
            else{
                  System.out.println("return null");
            }
            }
            catch(Exception e){
                  e.printStackTrace();
            }
            tx.commit();
            session.close();


      }
/*-------------------------------------------*/
      @Test
      public void testGetSearchData() {
          System.out.println("testGetSearchData>>>");

                  Transaction tx=null;

                System.out.println("testGetSearchData");
                String fdate="12/05/2016";
                String tdate="12/05/2016";
                System.out.println("fdate============" + fdate);
                System.out.println("tdate============" + tdate);
                try{
                    tx=session.beginTransaction();

                List<Object[]> list =sessionFactory.getCurrentSession().createQuery
                        ("select publicationId,documentId,documentType,languageCode,processStartDate,eventLogPid,eventType from EventLog where processStartDate between "+"'"+fdate+"'"+" and "+"'"+tdate+"'" ).list();

                tx.commit();

                List<Map<String, Object>> activeTeamMap = new ArrayList<Map<String, Object>>();
                if (list != null) {
                    for (Object[] obj : list) {
                        Map<String, Object> dropDownData = new HashMap<String, Object>();
                        dropDownData.put("publicationId", obj[0]);
                        dropDownData.put("documentId", obj[1]);
                        dropDownData.put("documentType", obj[2]);
                        dropDownData.put("languageCode", obj[3]);
                        dropDownData.put("processStartDate", obj[4]);
                        dropDownData.put("publicationType", obj[5]);
                        activeTeamMap.add(dropDownData);
                        System.out.println("activeTeamMap==vbnbvn==" + activeTeamMap);
                    }

                } else {

                }
                }
                catch(Exception ex){
                    ex.printStackTrace();
                }
                tx.commit();
                session.close();
    }

      @Test
      public void testGetEventLogDetails() {
        Transaction tx=null;
        String eventId="";
        System.out.println(">>>>>>>>>eventId>>>>testGetEventLogDetails>>>>>>"+eventId);
        String json=null;
        try{
            tx=session.beginTransaction();
            @SuppressWarnings("unchecked")
            List<Object[]> list= sessionFactory.getCurrentSession().createQuery
                    ("select eventDetailLogPid,documentId,docLoadStatus,processStartDate from EventDetailLog where eventLogPid="+eventId).list();

            Gson gson = new Gson();

            List<Map<String, Object>> activeTeamMap = new ArrayList<Map<String,Object>>();

            if (list != null) {

                for (Object[] obj : list) {
                    Map<String, Object> dropDownData = new HashMap<String, Object>();
                    dropDownData.put("eventDetailLogPid",obj[0]);
                    dropDownData.put("documentId",obj[1]);
                    dropDownData.put("docLoadStatus",obj[2]);
                    dropDownData.put("processStartDate",obj[3]);
                    activeTeamMap.add(dropDownData);


                    System.out.println("activeTeamMap==vbnbvn=="+activeTeamMap);
                  json = gson.toJson(activeTeamMap);  
                  System.out.println(json);
                }

        }
            else{

            }
            System.out.println("acticeteammap>>>>>"+activeTeamMap);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
}
}

testGetPaginationData的测试用例运行正常。但是当我尝试将会话对象重用于其他方法时,我正在解决以下错误:

org.hibernate.HibernateException: No CurrentSessionContext configured!
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012)
    at com.hp.legacyloader.controller.DashboardControllerTest.testGetSearchData(DashboardControllerTest.java:140)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

谁能告诉我这里做错了什么?我知道它根本不是一个干净的代码,但我是Java新手....

1 个答案:

答案 0 :(得分:0)

您不需要在之前的陈述中session=sessionFactory.openSession();

在你所有的测试中使用 sessionFactory.getCurrentSession().我觉得应该解决你的问题。

同时使用openSession

替换首次测试中的getCurrentSession来电