Reputation: 959
I'm writing unit tests for Android code using the Robolectric gradle test runner. The code I'm testing happens to be hitting date formatting methods that use the following format:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
We store Unix Time milliseconds as strings in that format, and just before sending it through the formatter to convert it back into a millisecond offset, we replace any instances of "Z" in the string with "+00:00". the call ends up looking like this:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
format.parse(validDateString.replace("Z", "+00:00));
This operation works fine in production code, but attempting to write unit tests has revealed previously unseen ParseExceptions. I first assumed it was because of a formatting issue with the date string I was injecting, but ParseExceptions are being thrown on strings saved from a date successfully parsed in prod code.
What could possibly be causing this radical difference in behavior?
Things I've tried already:
-Checked date formatting
-This DateFormat is actually a global static variable. I'm aware that they're not thread-safe, but inlining all static references with new instances yields the same results.
UPDATE: Partial stack trace
java.text.ParseException: Unparseable date: "2016-02-20T19:47:33.262+00:00"
at java.text.DateFormat.parse(DateFormat.java:357)
...nothing else useful
Additionally, I should mention that we use a complementary method that stores milliseconds as a String:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = new Date(unixTime);
String validDateString = format.format(date);
return validDateString.replace("+0000", "Z");
Note that we're replacing 4 0's without a colon, whereas the method that fails appends 00:00. That said, the not-quite-complementary operations work fine in production, but fail in unit tests.
Upvotes: 2
Views: 1828
Reputation: 26
Try setting your string for unit test directly:
String validDateString = "2016-02-20T19:47:33.262+0000"; // remove the colon
I had the same issue when running Robolectric. As per this issue on GitHub, replacing +00:00
with +0000
fixed the issue for me.
Upvotes: 1