【问题标题】:Mocking a static method模拟静态方法
【发布时间】:2015-11-24 06:30:41
【问题描述】:

以下是我要测试的方法。我正在使用 TestNG 框架进行单元测试。

class Random{

    List<String> namesOfLinks;

    public List<String> methodIwantToTest(List<String> cktNames) {
            Map<String, Graph> maps =   DataBaseReader.getGraphs(cktNames);
            for (Entry<String, Graph> entry : maps.entrySet()) {
                graphList.add(entry.getValue().getName());
            }
    }

    return namesOfLinks;
}

我正在为上述类中的方法“methodIwantToTest”编写测试用例。我可以提供一些虚拟的 cktNames 并让方法执行如下。

@Test (dataProvider = "dp")
public void test_methodIwantToTest(List<String> cktNames, List<String> expectedLinkNames){
    Random rm = new Random();
    List<String> actual = rm.methodIwantToTest(cktNames);
    Assert.assertEquals(actual,expectedLinkNames);
} 

现在问题来了。当我在“rm”引用上调用实际方法时,它有一个对另一个 API 的静态方法调用。它必须返回一些东西才能让我的“方法”起作用。我在互联网上搜索并找到“easymock”作为解决方案。但我无法使用“easyMock”来模拟静态方法(DataBaseReader.getGraphs())。我必须模拟该方法,以便它返回定义类型的映射。任何建议都会很棒。 谢谢!!

其他问题涉及如何测试静态方法。但我的是在测试实例方法时模拟静态方法。

【问题讨论】:

  • 您也不能使用 easymock 模拟静态方法。您需要使用 powerMock。

标签: java unit-testing testng easymock


【解决方案1】:

您需要PowerMock 直接模拟静态方法。见https://github.com/jayway/powermock/wiki/TestNG_usage

【讨论】:

    【解决方案2】:

    我建议将适配器模式与依赖注入技术结合使用。创建一个包含您要模拟的所有方法的接口:

    public interface IDatabase {
        Map<String, Graph> getGraphs(List<String> names);
    }
    

    很明显,Database 没有实现你刚刚发明的接口(反正方法是static),但是你可以创建一个适配器类:

    public class DataBaseReaderAdapter implements IDatabase {
        public Map<String, Graph> getGraphs(List<String> names) {
            return DataBaseReader.getGraphs(names);
        }
    }
    

    把这个类的一个实例作为你要测试的类的构造函数参数:

    public class Random {
        private readonly IDatabase _database;
    
        public Random(IDatabase database) {
            _database = database;
        }
    }
    

    当你想调用方法时:

    Map<String, Graph> maps = _database.getGraphs(cktNames);
    

    在您的测试中,使用任何模拟框架创建IDatabase 的模拟,并将该模拟传递给Random

    虽然这种技术一开始可能看起来相当复杂,但它往往会带来更好的设计,其中类的依赖关系更加明显,并且一切都变得更容易测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多