Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 模拟Locale.forLanguageTag_Java_Unit Testing_Mockito_Junit4_Powermock - Fatal编程技术网

Java 模拟Locale.forLanguageTag

Java 模拟Locale.forLanguageTag,java,unit-testing,mockito,junit4,powermock,Java,Unit Testing,Mockito,Junit4,Powermock,我试图对一个方法进行单元测试 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

我试图对一个方法进行单元测试

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
。如何解决这个问题?

一种方法(忽略当前错误的原因)是将
Locale
对象包装在可以正确模拟的立面中。然后可以将该对象作为字段/构造函数参数传递到类中

例如

然后在测试用例中,您可以在构建
上下文
对象之前模拟
LocalResolver

我总是喜欢这样的方法,而不是试图模拟具体的类。它的好处往往超出了测试的易用性。

我的案例的解决方案是
public interface LocaleResolver {    
  // add signatures for the methods you care about in Locale (only)
}

public class PlatformLocaleResolver implements LocaleResolver {
  // delegate all methods to the corresponding `Locale` methods
}

public class Context {
  // take LocaleResolver in constructor
  // (or, if preferred, expose a setter to adjust a class field)
}