I’m working on some unit tests for localization in our Android app. Right now my unit test checks all of our different format strings for all of our different locales to make sure the translators didn’t mess them up (which they tend to do). Basically I’m making sure that calling String.format() won’t throw a format exception.
The only downside is I need to manually add every string to the test. I’m working on a replacement test that uses reflection to find every string in R.string. Getting the strings isn’t a problem, but is there any easy way to determine the number and types of arguments a format string expects?
String.format() doesn’t complain if you pass it too many arguments so I could probably just pass a big array of Integers (which could get unboxed to %d or toString()’ed to %s) and look for format exceptions. Still, it would be a little nicer if I could pass the correct types of arguments in the correct amounts 🙂
Honestly, I think the method of checking for an
Exceptionis the best one you’ll come across without using your own fully-fledged parser.If you are seriously interested in writing a code to find all the elements (that will be come arguments) from the
format(...)method ofFormatter.java(I can’t find an anchor, so you just have to control+fformat(Loand you’ll find it). This code is also available in the SDK undersources\android-16\java\util, in the private methoddoFormat.It’s actually a relatively simple code once you learn the methods it uses to find each section and parse it. I think with a bit of work, and perhaps a bit of copy-paste from
Formatter, you could set up your very own code that would simply find the elements of theString, instead of substituting them.