如何在Mockito测试用例中提供LocaleInfo?

时间:2012-10-16 05:18:46

标签: java gwt mockito

我有一个使用以下代码行的方法:

   1. DateTimeFormat serverFormat = DateTimeFormat.getFormat("MM/dd/yyyy");
   2. DateTimeFormat displayFormat = DateTimeFormat.getFormat("MMM dd, yyyy");
   3. Date thisDate = serverFormat.parse(prices.getCheckInDate());

当我从我的测试用例(Mockito)中调用此方法时,第1行会出现 NullPointerException

我相信它是由于Locale而发生的。我对Locales了解不多。
请看看是否有人可以提供帮助。
我也在粘贴堆栈痕迹 测试它的正确方法是什么?我可以以某种方式从我的测试用例中提取Locale信息吗?

testSetupMyTable(MyViewTest)java.lang.NullPointerException
    at com.google.gwt.i18n.client.LocaleInfo.ensureDateTimeFormatInfo(LocaleInfo.java:201)
    at com.google.gwt.i18n.client.LocaleInfo.getDateTimeFormatInfo(LocaleInfo.java:159)
    at com.google.gwt.i18n.client.DateTimeFormat.getDefaultDateTimeFormatInfo(DateTimeFormat.java:808)
    at com.google.gwt.i18n.client.DateTimeFormat.getFormat(DateTimeFormat.java:625)


    at MyView.setupMyView(MyView.java:109)
    at MyViewTest.testSetupMyTable(MyViewTest.java:49)



谢谢,
莫希特

4 个答案:

答案 0 :(得分:1)

我在Util类中封装了DateTime格式化逻辑:

class Util {
  formatDate() {}
}

现在我在嘲笑实用工具类的方法。 我想我不必担心DateTimeFormat API的测试,因为它已经过测试。

在这种特殊情况下,我的测试并不要求日期转换是准确的,所以这个解决方案工作正常,但是如果我希望日期转换准确怎么办呢?

谢谢, 莫希特

答案 1 :(得分:1)

您最好使用 GwtMockito 。想象一下,您想要测试格式化日期的复合材料:

public class MyComposite extends Composite {

    private static final DateTimeFormat FORMATTER = DateTimeFormat.getFormat("dd MMM yy");

    private Label labelName, labelDate;

    @Override
    public void updateHeaderData(String userName, Date dateToShow) {
        labelName.setText(messages.hiUser(userName));
        labelDate.setInnerText(FORMATTER.format(dateToShow));
    }
}

测试避免使用我的模式的异常:

@RunWith(GwtMockitoTestRunner.class)
public class CompositeToTest {

    MyComposite composite;
    @GwtMock
    LocaleInfoImpl infoImpl;

    @Before
    public void setUp() throws Exception {
        com.google.gwt.i18n.client.DateTimeFormatInfo mockDateTimeFormatInfo =
            mock(com.google.gwt.i18n.client.DateTimeFormatInfo.class);
        when(infoImpl.getDateTimeFormatInfo()).thenReturn(mockDateTimeFormatInfo);
        String[] months =
            new String[] {"ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"};
        when(mockDateTimeFormatInfo.monthsShort()).thenReturn(months);
    }

    @Test
    public void should_whenUpdateHeaderData() throws Exception {
        // Given
        composite = new MyComposite();

        // When
        composite.updateHeaderData("pepito", new Date());

        // Then
        verify(labelDate).setText(anyString());
    }
}

答案 2 :(得分:0)

你甚至不需要模拟静态方法,你可能只是模拟DateTimeFormat。

DateTimeFormat serverFormat = mock(DateTimeFormat.class);
Date date = new Date();
when(serverFormat().parse(any())).thenReturn(date);

答案 3 :(得分:0)

您可以使用GwtMockitoTestRunner来运行单元测试。这应该可以解决你的问题。

@RunWith( GwtMockitoTestRunner.class )
public class TestClass
{
  ...
}
相关问题