gpt4 book ai didi

java - PowerMock/EasyMock : Set expectation on final method that would throw exception

转载 作者:行者123 更新时间:2023-12-01 12:08:19 25 4
gpt4 key购买 nike

如果我根本无法安全地调用该方法,如何设置对 final方法的期望? PowerMock 应该确保调用被模拟,但我什至无法到达那个阶段:

WithFinal.java:

public class WithFinal {
public final void finalMethod() {
throw new RuntimeException();
}
}

CallsFinal.java:

public class CallsFinal {
private WithFinal withFinal;

public CallsFinal(WithFinal withFinal) {
this.withFinal = withFinal;
}

public void callFinal() {
withFinal.finalMethod();
}
}

PowerMockTest.java:

import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;

import static org.powermock.api.easymock.PowerMock.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CallsFinal.class)
public class PowerMockTest {
@Test public void testFinal() {
WithFinal mock = createMock(WithFinal.class);
CallsFinal callsFinal = new CallsFinal(mock);
mock.finalMethod();
EasyMock.expectLastCall().atLeastOnce();
replay(mock);
callsFinal.callFinal();
verify(mock);
}
}

我在第一次调用 mock.finalMethod() 时得到一个 RuntimeException,这是有道理的,但我认为 PowerMock 的全部意义在于使这成为可能?

最佳答案

测试类中存在一个简单的错误:它应该是 @PrepareForTest(WithFinal.class),而不是 @PrepareForTest(CallsFinal.class)

PowerMock 仅要求在从 JRE 模拟系统类时为测试准备好调用类;否则,需要准备的是要模拟的类本身。

最后,我要提到的是另一个可以在这里使用的模拟库,它是我开发的:JMockit。有了它,测试可以写成:

import org.junit.*;
import mockit.*;

public class JMockitTest {
@Tested CallsFinal callsFinal;
@Injectable WithFinal mock;

@Test public void testFinal() {
new Expectations() {{ mock.finalMethod(); }};

callsFinal.callFinal();
}
}

关于java - PowerMock/EasyMock : Set expectation on final method that would throw exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27420989/

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