Search code examples
javagwtmockito

How to provide LocaleInfo in Mockito test cases?


I have a method which uses the following lines of code:

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

When I call this method from my test case(Mockito), a NullPointerException occurs at line# 1.

I believe it is happening due to Locale. I don't know much about Locales. I am pasting the stack trace too.

What is the right way to test it? Can I somehow provide Locale info from my test case?

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)

Solution

  • I encapsulated the DateTime formatting logic in a Util class:

    class Util {
      formatDate() {}
    }
    

    And now I am mocking the method of utility class. I guess I don't have to be worried about the testing of DateTimeFormat API as it is already tested.

    In this particular case My test does not require the date conversion to be exact so this solution works fine, but what if I want the date conversion to be exact?