2009-11-09 139 views
0

這是對我的previous question的後續問題。使用JUnit測試ServiceLocator

我試圖寫測試用例我的ServiceLocator類,但它給了我下面的錯誤:

com/iplanet/ias/admin/common/ASException 
java.lang.NoClassDefFoundError: com/iplanet/ias/admin/common/ASException 
     at java.lang.ClassLoader.defineClass1(Native Method) 

我的測試用例:

public void testServiceLocator() throws UivException, NamingException 
{ 
    DataSource ds = ServiceLocator.getInstance().getDataSource("jdbc/RSRC/my/mydb"); 
    //I have not put any assert statements because i know above line is failing 
} 

上面的代碼上getInstance()方法失敗看起來這像這樣:

static public ServiceLocator getInstance() throws UivException { 
    try { 
     if (me == null) { 
      synchronized(ServiceLocator.class) { 
      me = new ServiceLocator(); 
      } 
     } 
     return me; 
    } 
    catch (UivException e) { 
      throw new UivException(ErrorCode.SERVICE_LOCATOR_ERROR, 
           ErrorCode.SERVICE_LOCATOR_LOOKUP_ERROR, 
           e.getMessage()); 
    } 
} 

我知道這個ServiceLocator工作正常因爲當我從前端測​​試我的應用程序時沒有問題。我寫這個測試用例的唯一原因是因爲我想測試我的DAO。併爲我測試我的DAO ServiceLocator必須工作(從JUnit)。

我不知道如何處理錯誤消息。有沒有人想提出一些我可以嘗試的方法,希望能夠奏效?

編輯:服務定位構造

private ServiceLocator() throws UivException { 
    try { 
     ic = new InitialContext(); 
     // System.out.println("Created the Initial Context"); 
     cache = Collections.synchronizedMap(new HashMap()); 
    } 
    catch (NamingException ne) { 
     throw new UivException(ErrorCode.SERVICE_LOCATOR_ERROR, 
           0, ne.getMessage()); 
    } 
    catch (NullPointerException e) { 
      throw new UivException(ErrorCode.SERVICE_LOCATOR_ERROR, 
           0, e.getMessage()); 
    } 
} 

回答

1

嗯,是com.iplanet.ias.admin.common.ASException上,當你調用你的測試類路徑?

您是否依賴應用程序服務器將JDBC驅動程序的庫存放在classpath中,還是自己部署它?

+0

我依靠應用程序服務器。因爲應用程序服務器已經擁有了所有我想編寫測試並與之相處的設置。 – Omnipresent 2009-11-09 02:27:36

+0

com.iplanet的東西似乎是Sun App Server的管理員屬性。這可能需要從應用服務器獲取JDBC資源。 ...但是應用服務器上未部署Junit測試... – Omnipresent 2009-11-09 02:31:08

+0

但是如果您的單元測試調用嘗試加載JDBC驅動程序的代碼,那麼在執行單元測試時,JDBC驅動程序需要位於類路徑中。 – 2009-11-09 03:41:54

2

實際上,錯誤很明顯:java.lang.NoClassDefFoundError: com/iplanet/ias/admin/common/ASException表示在運行時找不到ASException的定義。

在應用程序服務器中運行時,此類由iPlanet Application Server提供,代碼運行良好。要在應用程序服務器上下文之外運行此代碼,您必須通過將其置於類路徑中進行「手動」提供。所以你必須將正確的iPlanet JAR添加到類路徑中(這是一個棘手的部分,你必須找到哪一個)。

此外,我可以看到您使用的是非參數構造函數InitialContext,因此您在應用程序服務器內運行時使用的是iPlanet的環境設置。在iPlanet之外(例如,對於單元測試),您必須自己爲iPlanet提供正確的JNDI屬性。爲此,您必須在類路徑中使用(至少)初始上下文工廠和提供程序URL來放置jndi.properties文件。例如:

java.naming.factory.initial=... 
java.naming.provider.url=... 

檢查您的iPlanet文檔的值。

0

我很好奇你爲什麼寫一個服務定位器。它是一項任務的一部分嗎?在現實世界中,依賴注入顯然是優越的選擇,使用Guice或Spring。

+0

不是不是一項任務。我們有舊的遺留代碼仍在使用JDBC(與ORM相比)。我試圖將這些遺留代碼變得更加「真實世界值得」。你有任何你想分享的關於彈簧注射的鏈接? – Omnipresent 2009-11-09 23:32:48