单元测试使用资源包的静态方法

use*_*486 1 java unit-testing junit4 mockito powermock

我已经阅读了很多关于使用Powermock和Mockito的文章,并尝试了很多不同的方法,但我仍然无法弄清楚如何对下面的静态方法进行单元测试.

public static Map<String, String> getEntries() {
    Map<String, String> myEntriesMap = new TreeMap<String, String>();
    ResourceBundle myEntries = ResourceBundle.getBundle(ENTRIES_BUNDLE);
    Enumeration<String> enumList = myEntries.getKeys();
    String key = null;
    String value = null;
    while (enumList.hasMoreElements()) {
        key = enumList.nextElement().toString();
        value = myEntries.getString(key);
        myEntriesMap.put(key, value);
    }
    return myEntriesMap;
}
Run Code Online (Sandbox Code Playgroud)

代码是包含大约30个这样的静态方法的(遗留)类的一部分,并且重构实际上不是一个选项.类似地,在一些其他静态方法中,正在检索DB连接.

例如:如何模拟资源包ENTRIES_BUNDLE并对此方法进行单元测试?我正在寻找一种可以普遍适用于所有静态方法的模式.

Jul*_*eau 8

使用ResourceBundle.getBundle(String,ResourceBundle.Control)获取ResourceBundle以缓存给定String的包.您可以将ResourceBundle.Control子类化,以提供您心中所需的任何类型的包.

@Test
public void myTest()
{
    // In your Test's init phase run an initial "getBundle()" call
    // with your control.  This will cause ResourceBundle to cache the result.
    ResourceBundle rb1 = ResourceBundle.getBundle( "blah", myControl );

    // And now calls without the supplied Control will still return
    // your mocked bundle.  Yay!
    ResourceBundle rb2 = ResourceBundle.getBundle( "blah" );
}
Run Code Online (Sandbox Code Playgroud)

这是子类控件:

ResourceBundle.Control myControl = new ResourceBundle.Control()
{
    public ResourceBundle newBundle( String baseName, Locale locale, String format,
            ClassLoader loader, boolean reload )
    {
        return myBundle;
    }
};
Run Code Online (Sandbox Code Playgroud)

这里有一种模拟ResourceBundle的方法(用单元测试所需的键/值填充TreeMap作为读者的练习):

ResourceBundle myBundle = new ResourceBundle()
{
    protected void setParent( ResourceBundle parent )
    {
      // overwritten to do nothing, otherwise ResourceBundle.getBundle(String)
      //  gets into an infinite loop!
    }

    TreeMap<String, String> tm = new TreeMap<String, String>();

    @Override
    protected Object handleGetObject( String key )
    {
        return tm.get( key );
    }

    @Override
    public Enumeration<String> getKeys()
    {
        return Collections.enumeration( tm.keySet() );
    }
};
Run Code Online (Sandbox Code Playgroud)


Rog*_*rio 5

您不需要模拟该ResourceBundle.getBundle方法。只需在测试源树中的适当位置创建一个“.properties”文件即可。这仍然是一个非常好的和有用的单元测试。