How to mock ResourceBundle.getString()?
Instead of mocking you can create a dummy ResourceBundle implementation, and then pass it as an argument to .thenReturn(resourceBundle)
:
import java.util.ResourceBundle;
ResourceBundle dummyResourceBundle = new ResourceBundle() {
@Override
protected Object handleGetObject(String key) {
return "fake_translated_value";
}
@Override
public Enumeration<String> getKeys() {
return Collections.emptyEnumeration();
}
};
// Example usage
when(request.getResourceBundle(any(Locale.class))).thenReturn(dummyResourceBundle)
If you need the actual keys and values, then you'll need to provide an implementation for getKeys()
, e.g. a hashmap for storage and key lookup.
@Powermockito did not worked as ResourceBundle.class have static final methods which were not easy to mock.
I tried.
In the Main Class extract your method inside another public method, and then overide it with implementaion.
Here ReviewEChannelApplicationMBean is my Controller, where i overrriden the getBundle.
ReviewEChannelApplicationMBean = spy(new ReviewEChannelApplicationMBean(){
@Override
public ResourceBundle getBundle(FacesContext fcContext) {
return TestDataBuilder.getResourceBundle();
}
});
//This Class i my TestDataBuilder using ListResourceBundle
public class TestDataBuilder {
public static ResourceBundle getResourceBundle() {
return new ListResourceBundle(){
@Override
protected Object[][] getContents() {
return contents;
}
private Object[][] contents = {
{"test1","01"},
{"test2","01"},
{"test3","01"},
{"test4","01"}
};
};
}
}
You'll find an example of solution below :
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ResourceBundle.class })
public class ResourceBundleTest {
@Test
public void getStringByPowerMock() throws Exception {
ResourceBundle resourceBundle = PowerMockito.mock(ResourceBundle.class);
Mockito.when(resourceBundle.getString(Mockito.anyString())).thenReturn("Hello world....");
System.out.println(resourceBundle.getString("keyword"));
}
}
I figured out a way to mock ResourceBundle by subclassing ResourceBundle.Control. My answer is here:
https://stackoverflow.com/a/28640458/290254
I prefer to avoid the dynamic bytecode rewriting (to remove final) of PowerMock, JMockit and friends, since Jacoco and other things seem to hate it.