GWT unit test case

2019-05-30 15:37发布

I was planning to write a unit test case for one of my helper methods in GWT.

Am getting error saying that ERROR: GWT.create() is only usable in client code! It cannot be called, for example, from server code. If you are running a unit test, check that your test case extends GWTTestCase and that GWT.create() is not called from within an initializer or constructor.

When I debug, I see that error is originating from the line

NumberFormat formatter = NumberFormat.getCurrencyFormat(); in my code. Kindly help.

This is my code :

TestCase:

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

Code to be Tested

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

}

1条回答
Deceive 欺骗
2楼-- · 2019-05-30 16:05

If getModuleName returns null then your test runs just like any other JUnit test, i.e. not in a GWT context.

Make getModuleName return the name of your module (the one you pass to the GWT Compiler, or the one you'll <inherit> in another GWT module) to switch to running as GWT.

查看更多
登录 后发表回答