2013-06-22 66 views
1

我正打算爲GWT中的一個輔助方法編寫單元測試用例。GWT單元測試用例

我得到的錯誤說錯誤:GWT.create()只能在客戶端代碼中使用!例如,它不能從服務器代碼中調用。如果您正在運行單元測試,請檢查您的測試用例是否擴展了GWTTestCase,並且GWT.create()不是從初始化程序或構造函數中調用的。

當我調試,我看到的錯誤是從我的代碼行

NumberFormat formatter = NumberFormat.getCurrencyFormat();始發。請幫助。

這是我的代碼:

測試用例:被測試

public class CurrencyFormatterTest extends GWTTestCase { 

    private CurrencyFormatter currencyFormatter = new CurrencyFormatter(); 

    public void testCurrencyFormatForActualCurrencyString() { 
     String formattedString = currencyFormatter.format(" 123456.78999"); 
     assertEquals("US$123,456.79", formattedString); 
    } 

@Override 
    public String getModuleName() { 
     return null; 
    } 
} 

代碼

public class CurrencyFormatter implements Formatter { 

    @Override 
    public String format(Object value) { 
     if (value == null || value.equals("")) { 
      return ""; 
     } 
     Double val = Double.parseDouble(value.toString()); 
     NumberFormat formatter = NumberFormat.getCurrencyFormat(); 
     String formattedValue = formatter.format(val); 
     return formattedValue; 
    } 

} 

回答

2

如果getModuleName回報null那麼你的測試運行,就像任何其他JUnit測試,即不是GWT上下文

製作getModuleName返回你的模塊(一個你傳遞給GWT編譯器,或者一個你會<inherit>在另一個GWT模塊)切換到運行如GWT的名稱。

+0

我也這麼做了。我發現案件的執行需要很長時間(比如4到5秒)。任何具體原因? – LPD

+0

['GWTTestCase'是原因](http://www.gwtproject.org/doc/latest/DevGuideTesting.html):它使用HtmlUnit「瀏覽器模擬」啓動Web服務器和DevMode會話。還可以看看[gwt-mockito](https://github.com/google/gwtmockito),[gwt-test-utils](https://github.com/gwt-test-utils/gwt-test- utils)以及GWT SDK中的GWTMockUtilities類。 –