在其他静态方法中模拟静态方法

时间:2014-11-14 15:11:35

标签: java mocking mockito powermock

我有一个小类,它返回由我的类路径中的message_xx.properties填充的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 in line:

Assert.assertNotNull(PropertiesUtils.loadProperties(zuluLocale));

1 个答案:

答案 0 :(得分:0)

好的,这是假的,问题,我需要做的就是:

PowerMockito.when(PropertiesUtils.loadProperties(zuluLocale)).thenCallRealMethod();
PowerMockito.when(PropertiesUtils.loadProperties(etruscanLocale)).thenCallRealMethod();