我如何用PowerMock&的Mockito? [英] How can I mock an instance of an enum class with PowerMock & Mockito?

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

问题描述

我试图按照这个非常类似的问题的答案提供的例子,但对我来说并不奏效。我收到以下错误消息:

I tried to follow the example offered in the answer to this very similar question, but it does not work for me. I get the following error message:

java.lang.IllegalArgumentException: Cannot subclass final class class com.myproject.test.support.ExampleEnumerable
    at org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:447)
    at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)
    at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
    at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
    at org.powermock.api.mockito.repackaged.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)
    at org.powermock.api.mockito.repackaged.ClassImposterizer.imposterise(ClassImposterizer.java:57)
    at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:110)
    at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:58)
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:143)

我需要一个简单的模拟实例,一个枚举类。我不需要嘲笑任何方法。

I need a simple mock instance of an enum class. I don't need to mock any of its methods.

这是我想要嘲笑的类:

public enum ExampleEnumerable implements IEnumerable<ExampleEnumerable> {
    EXAMPLE_ENUM_1("Test Enum 1"),
    EXAMPLE_ENUM_2("Test Enum 2");

    final String alias;

    ExampleEnumerable(final String alias) {
        this.alias = alias;
    }

    @SuppressWarnings({"VariableArgumentMethod", "unchecked"})
    @Override
    public @Nullable
    String getAlias(final @Nonnull IEnumerable<? extends Enum<?>>... context) {
        return alias;
    }
}

我有以下TestNG设置:

I have the following TestNG setup:

import static org.powermock.api.mockito.PowerMockito.mock;

@PrepareForTest({ ExampleEnumerable.class})
@Test(groups = {"LoadableBuilderTestGroup"})
public class LoadableBuilderTest {

    private ExampleEnumerable mockEnumerable;

    @BeforeMethod
    public void setUp() {
        mockEnumerable = mock(ExampleEnumerable.class);
    }
}


推荐答案

通过扩展处理此类事物的PowerMockTestCase类来为TestNG工作:

I got this working by extending the PowerMockTestCase class that handles this kind of thing for TestNG:

@PrepareForTest(TestEnumerable.class)
@Test(groups = {"LoadableBuilderTestGroup"})
public class LoadableBuilderTest extends PowerMockTestCase {

 private TestEnumerable mockEnumerable;

 @SuppressWarnings("unchecked")
    @BeforeMethod
    public void setUp() {
        mockEnumerable = PowerMockito.mock(TestEnumerable.class);

    }
}

这篇关于我如何用PowerMock&amp;的Mockito?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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