如何用静态方法模拟? [英] How to mock with static methods?

查看:21
本文介绍了如何用静态方法模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是模拟对象的新手,但我知道我需要让我的类实现接口才能模拟它们.

I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.

我遇到的问题是,在我的数据访问层,我想要静态方法,但我不能在接口中放置静态方法.

The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface.

解决这个问题的最佳方法是什么?我应该只使用实例方法(这似乎是错误的)还是有其他解决方案?

What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?

推荐答案

我会使用方法对象模式.有一个 this 的静态实例,并在静态方法中调用它.应该可以子类化以进行测试,具体取决于您的模拟框架.

I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.

即在您的类中使用静态方法有:

i.e. in your class with the static method have:

private static final MethodObject methodObject = new MethodObject();

public static void doSomething(){
    methodObject.doSomething();
}

并且您的方法对象可以是一个非常简单、易于测试的对象:

and your method object can be a very simple, easily-tested:

public class MethodObject {
    public void doSomething() {
        // do your thang
    }
}

这篇关于如何用静态方法模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆