gpt4 book ai didi

java - 如何使用 PowerMock 和 Mockito 模拟枚举类的实例?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:00 28 4
gpt4 key购买 nike

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

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)

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

这是我要模拟的类:

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 设置:

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

最佳答案

您需要使用 PowerMockRunner 运行它

例如。

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

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

关于java - 如何使用 PowerMock 和 Mockito 模拟枚举类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30127057/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com