簡體   English   中英

使用JUnit測試ServiceLocator

[英]Testing ServiceLocator using JUnit

這是我先前問題的跟進問題

我正在嘗試為我的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 )。

我不知道如何處理錯誤消息。 是否有人想建議我可以嘗試的東西,希望能成功?

編輯:ServiceLocator構造函數

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

實際上,該錯誤非常清楚: java.lang.NoClassDefFoundError: com/iplanet/ias/admin/common/ASException指示在運行時找不到ASException的定義。

在應用程序服務器中運行時,此類由iPlanet Application Server提供,並且代碼運行良好。 要在應用程序服務器上下文之外運行此代碼,必須將其放在類路徑中以“手動”方式提供。 因此,您必須在類路徑中添加正確的iPlanet JAR(這是棘手的部分,您必須找到哪個)。

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

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

檢查您的iPlanet文檔中的值。

那么,調用測試時,類路徑上是否存在com.iplanet.ias.admin.common.ASException

您是依靠應用服務器在其類路徑中包含JDBC驅動程序的庫,還是自己部署它?

我很好奇您為什么要編寫服務定位器。 這是作業的一部分嗎? 在現實世界中,使用Guice或Spring顯然是依賴注入是更好的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM