0
靜態方法我有小班返回Properties對象由位於我的類路徑message_xx.properties填充:嘲笑其他靜態方法
public class PropertiesUtils {
public static Properties loadProperties(Locale locale) {
try {
ClassLoader loader = getClassLoader();
Properties properties = new Properties();
String filePath = "messages_" + locale.getLanguage().toLowerCase() + ".properties";
InputStream is = loader.getResourceAsStream(filePath);
properties.load(is);
is.close();
return properties;
} catch (Exception e) {
log.error("Error loading properties by locale "+locale, e);
return null;
}
}
public static ClassLoader getClassLoader(){
return PropertiesUtils.class.getClassLoader();
}
}
一切工作正常,但我想創建單元測試此。我想模擬方法「getClassLoader」返回我想要在我的junit測試上下文中的一些特定的InputStream。
@RunWith(PowerMockRunner.class)
@PrepareForTest(value=PropertiesUtils.class)
public class PropertiesUtilsTest {
@Mock
private Locale zuluLocale;
@Mock
private Locale etruscanLocale;
@Mock
private ClassLoader mockClassLoader;
@Before
public void init(){
Mockito.when(zuluLocale.getLanguage()).thenReturn("zulu");
Mockito.when(etruscanLocale.getLanguage()).thenReturn("etruscan");
Mockito.when(mockClassLoader.getResourceAsStream("messages_zulu.properties")).thenReturn(IOUtils.toInputStream("2=esal"));
Mockito.when(mockClassLoader.getResourceAsStream("messages_etruscan.properties")).thenReturn(IOUtils.toInputStream("2=ezimbili"));
PowerMockito.mockStatic(PropertiesUtils.class);
PowerMockito.when(PropertiesUtils.getClassLoader()).thenReturn(mockClassLoader);
}
@After
public void finalize(){
zuluLocale = null;
etruscanLocale = null;
}
@Test
public void loadPropertiesTest(){
Assert.assertNull(PropertiesUtils.loadProperties(new Locale("en")));
Assert.assertNotNull(PropertiesUtils.loadProperties(zuluLocale));
Assert.assertNotNull(PropertiesUtils.loadProperties(etruscanLocale));
Assert.assertEquals("esal", PropertiesUtils.loadProperties(zuluLocale).getProperty("2"));
Assert.assertEquals("ezimbili", PropertiesUtils.loadProperties(etruscanLocale).getProperty("2"));
}
}
該測試失敗爲AssertionFailedError異常一致:
Assert.assertNotNull(PropertiesUtils.loadProperties(zuluLocale));
更可測試類的設計將是接受'InputStream'作爲'loadProperties'方法中的一個參數。或者創建一個採用'InputStream'並測試的包私有方法。您可以使用公共方法調用包私有方法。注意:你的'finalize()'方法對我來說似乎是多餘的。 – 2014-11-14 15:37:27