0
我試圖單元測試,做嘲諷Locale.forLanguageTag
public static Context fromLanguageTag(final String languageTag) {
final Context context = new Context();
final Locale locale = Locale.forLanguageTag(languageTag);
context.language = locale.getLanguage().length()==3 ? locale.getLanguage() : locale.getISO3Language();
return context;
}
爲了測試,我需要模擬java.util.Locale
的方法。我使用PowerMock和的Mockito:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Locale.class })
public class ContextTest {
public void testFromLanguageTag() throws Exception {
mockStatic(Locale.class);
final Locale mockLocale = mock(Locale.class);
when(mockLocale.getLanguage()).thenReturn(LANGUAGE_3_OUTPUT);
when(mockLocale.getISO3Language()).thenReturn(LANGUAGE_ISO);
when(Locale.forLanguageTag(Mockito.eq(LANGUAGE_TAG_LONG_INPUT))).thenReturn(mockLocale);
final Context c = Context.fromLanguageTag(LANGUAGE_TAG_LONG_INPUT);
assertThat(c.getLanguage()).isEqualTo(LANGUAGE_3_OUTPUT);
}
}
但似乎嘲笑的方法從mockLocale
調用從來不被稱爲;相反,我從java.util.Locale.getISO3Language
(我想模擬)得到java.util.MissingResourceException
。如何解決這個問題?
我的案例的解決方案是[模擬系統類獲取系統屬性](http://stackoverflow.com/a/20408354) –