private void handleError() { String msg = "Failed to retrieve the locale for this page";
logger.error(msg); throw new RuntimeException(msg); }
}
You can see that there’s one method: getResourceString(...), which given a key will retrieve a resource string from a bundle. In order to make this work a little more efficiently, I’ve lazily loaded my resource bundle, and once loaded, I call bundle.getString(key) to retrieve my resource. To test this I’ve written a PowerMock JUnit test:
final String key = "DUMMY";
Exception e = new MissingResourceException(key, key, key);
expect(bundle.getString(key)).andThrow(e);
replayAll();
instance.getResourceString(key); }
@Test(expected = MissingResourceException.class) public final void testGetResourceStringWithBundleMissing() {
mockStatic(ResourceBundle.class); final String key = "DUMMY";
Exception e = new MissingResourceException(key, key, key);
expect(ResourceBundle.getBundle("SomeBundleName", Locale.ENGLISH)).andThrow(e);
replayAll();
instance.getResourceString(key); }
}
In the code above I’ve taken the unusual step of including the import statements. This is to highlight that we’re using PowerMock’s versions of the import statics and not EasyMock’s. If you accidentally import EasyMock’s statics, then the whole thing just won’t work.
There are four easy steps in setting up a test that mocks a static call:
Use the PowerMock JUnit runner:
@RunWith(PowerMockRunner.class)
Declare the test class that we’re mocking:
@PrepareForTest(UsesResourceBundle.class)
Tell PowerMock the name of the class that contains static methods:
mockStatic(ResourceBundle.class);
Setup the expectations, telling PowerMock to expect a call to a static method:
The rest is plain sailing, you set up expectations for other standard method calls and the tell PowerMock/EasyMock to run the test, verifying the results:
final String key = "DUMMY"; final String message = "This is a Message";
expect(bundle.getString(key)).andReturn(message);
replayAll();
String result = instance.getResourceString(key);
verifyAll();