1

我打算为我在 GWT 中的一个辅助方法编写一个单元测试用例。

我收到错误说ERROR: 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;
    }

}
4

1 回答 1

2

如果getModuleName返回null,那么您的测试就像任何其他 JUnit 测试一样运行,即不在GWT 上下文中。

返回您的模块的名称(getModuleName您传递给 GWT 编译器的名称,或者您将<inherit>在另一个 GWT 模块中使用的名称)以切换到作为 GWT运行。

于 2013-06-22T16:15:40.047 回答