如何使用PowerMock& amp模拟枚举类的实例?的Mockito?

时间:2015-05-08 15:05:22

标签: java enums mockito powermock powermockito

我试着按照这个非常相似的问题的答案提供的例子,但它对我不起作用。我收到以下错误消息:

word

我需要一个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) 的简单模拟实例。我不需要嘲笑它的任何方法。

这是我想要模拟的课程:

enum class

我有以下TestNG设置:

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;
    }
}

3 个答案:

答案 0 :(得分:3)

您需要使用PowerMockRunner

运行此功能

例如

@RunWith(PowerMockRunner.class)
@PrepareForTest({ ExampleEnumerable.class})
@Test(groups = {"LoadableBuilderTestGroup"})
public class LoadableBuilderTest {
    private ExampleEnumerable mockEnumerable;

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

答案 1 :(得分:3)

我通过扩展PowerMockTestCase类来为TestNG处理这类事情而得到了这个工作:

 public void removePhoneKeypad() {
    InputMethodManager inputManager = (InputMethodManager) view
            .getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    IBinder binder = view.getWindowToken();
    inputManager.hideSoftInputFromWindow(binder,
            InputMethodManager.HIDE_NOT_ALWAYS);
}

答案 2 :(得分:1)

大家好,我的工作如下:

首先在pom.xml上添加功率模拟:

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.4</version>
    <scope>test</scope>
</dependency>

,然后在我的课上:

@RunWith(PowerMockRunner.class)
@PrepareForTest({EnumClass.class})
public class EnumClassTest{
    private EnumClassTest enumClassTest;
    
    @Before
    public void setUp() {
        enumClassTest = mock(EnumClassTest.class);
    }
    
    @Test
    public void someMethod() {
        //My code test here
    }