简体   繁体   English

如何使用 jmockit 模拟枚举 singleton?

[英]How to mock enum singleton with jmockit?

I have a dependency on an enum singleton class like我依赖于枚举 singleton class 之类的

public enum SingletonObject {
  INSTANCE;
  
  SingletonObject() {
    // some annoying initialization
  }

  public callDB() {
    this.num = num;
  }

}

I am trying to test a class like我正在尝试测试 class 之类的

public class MyClass {
  public void doSomething() {
    // some code
    SingletonObject.INSTANCE.callDB();
  }
}

Following this answer , I've tried simply testing the mock with the following code, but I seem to be running into problems with the enum calling its constructor按照这个答案,我尝试使用以下代码简单地测试模拟,但我似乎遇到了枚举调用其构造函数的问题

public class MyClassTest {
    @Mocked
    private SingletonObject singleton;
    
    @Before
    public void setup() {
        Deencapsulation.setField(SingletonObject.class, "INSTANCE", singleton);
    }
    
    @Test
    public void test() {
        assertSame(singleton, SingletonObject.INSTANCE);
    }
}

Using an interface seems somewhat promising, but I question whether that is the best way of going about this problem. 使用接口似乎有点前途,但我怀疑这是否是解决这个问题的最佳方法。

It looks like PowerMockito is promising as well, but I would like to save that as a last resort for various reasons.看起来PowerMockito 也很有希望,但出于各种原因,我想将其保存为最后的手段。

So how can I mock this enum singleton without invoking its constructor?那么如何在不调用它的构造函数的情况下模拟这个枚举 singleton 呢?

Try something like this.尝试这样的事情。 This creates a partial-mock of 'MyClass' and a Mock SingletonObject, calls the (real) doSomething method of MyClass, and confirms that the (mock) callDB() method of SingletonObject is invoked by it precisely once.这将创建一个“MyClass”的部分模拟和一个模拟 SingletonObject,调用 MyClass 的(真实)doSomething 方法,并确认 SingletonObject 的(模拟)callDB() 方法被它调用一次。

@Test
public void testdoSomething(
    @Mocked final SingletonObject singleton)
{
    final MyClass clz = new MyClass();

    new Expectations(clz)
    {
        {
            SingletonObject.INSTANCE.callDB();
            times = 1;
        }
    };
    clz.doSomething();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM