如何在Java中模拟局部变量? [英] How to mock local variables in java?

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

问题描述

在这种情况下?

class A {
  public void f() {
    B b = new B();
    C c = new C();
    // use b and c, and how to modify their behaviour?
  }
}

如何用PowerMockEasyMock充实我的想法?

How can I fullfill my idea with PowerMock and EasyMock?

出于测试原因,我不想更改紧凑代码.

I don't want to change my compact code for test reasons.

推荐答案

您可以执行此操作,请参见Matt Lachman的答案.但是,不建议采用这种方法.有点黑.

You can do this, see the answer by Matt Lachman. That approach isn't recommended however. It's a bit hacky.

最好的方法是将依赖对象的创建委托给工厂模式,并将工厂注入到您的A类中:

The best approach would be to delegate creation of your dependant objects to a factory pattern and inject the factories into your A class:

class BFactory {

    public B newInstance() {
        return new B();
    }
}

class CFactory {

    public C newInstance() {
        return new C();
    }
}

class A {

    private final BFactory bFactory;
    private final CFactory cFactory;

    public A(final BFactory bFactory, final CFactory cFactory) {
        this.bFactory = bFactory;
        this.cFactory = cFactory;
    }

    public void f() {
        B b = bFactory.newInstance();
        C c = cFactory.newInstance();
    }
}

然后您将模拟工厂以返回依赖类的模拟实例.

You would then mock the factories to return mock instances of the dependent classes.

如果由于某种原因这不可行,则可以在A类中创建工厂方法

If for some reason this is not viable then your can create factory methods in the A class

class A {

    public void f() {
        B b = newB();
        C c = newC();
    }

    protected B newB() {
        return new B();
    }

    protected C newC() {
        return newC();
    }
}

然后,您可以使用模拟那些工厂方法的spy.

Then you can use a spy that mocks those factory methods.

这篇关于如何在Java中模拟局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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