2016-12-13 9 views
0

私は次のクラスのためにJunitテストケースを作成しようとしています。私は1つのテストケースを正常に実行することができます。私はサーバーを介してデータベースからデータを取得するためにセッションを使用しています。 セッションオブジェクトを別のインスタンスとして使用しようとしています。最初の方法では動作しますが、他の方法では動作しません。私は愚かな間違いをしていることを知っています。ここ は私のクラスである:JUnitテストケースで複数のセッションを使用できますか?

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; 
    }  



} 

は、次の私の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のためのテストケースが正常に動作しています。しかし、私は、私は次のエラーをgetiingています他の方法のためにセッションオブジェクトを再利用しようとしていますよう:

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の初心者です....

+0

私がその後、メソッドの残りの部分をチェックするか、単一のテストメソッド(テストケース) – Jobin

+0

のためのセッションを使用した方がよいとあなたの最初のテストであなたのopenSession呼び出しを置き換えますか? – srishti

+0

あなたはそれを正しくやっています。あなたはそれを前もってcreatringしています。必要なオブジェクトをリセットする必要がある場所です。 – Jobin

答えて

0

あなたの前のステートメントでsession=sessionFactory.openSession();をする必要はありません。

すべてのテストでは、 sessionFactory.getCurrentSession().を使用してください。問題が解決するはずです。

またgetCurrentSession

+0

ちょっと、私のopensession呼び出しを変更しようとしました。メソッドをgetCurrentSessionに設定します。No CurrentSessionContextを設定しています – srishti

関連する問題