gpt4 book ai didi

java - 如何使用 PowerMock 模拟 ServletFileUpload 的创建?

转载 作者:行者123 更新时间:2023-12-01 18:42:52 29 4
gpt4 key购买 nike

我想测试在某个类中是否创建了 ServletFileUpload 类的实例。

这是正在测试的类:

public class ClassBeingTested {
public void run()
{
new ServletFileUpload();
}
}

这是测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ServletFileUpload.class)
public class MyTest {
@Test
public void testServletUploadCreation() throws Exception {
// Setup mock
final ServletFileUpload fileUpload = createMockAndExpectNew(
ServletFileUpload.class);
replay(fileUpload, ServletFileUpload.class);

// Invoke method under test
final ClassBeingTested objectUnderTest = new ClassBeingTested();
objectUnderTest.run();

// Verify that ServletFileUpload instance was created
verify(fileUpload, ServletFileUpload.class);
}

}

verify 语句抛出以下异常:

java.lang.AssertionError: 
Expectation failure on verify:
org.apache.commons.fileupload.servlet.ServletFileUpload(): expected: 1,
actual: 0
at org.powermock.api.easymock.internal.invocationcontrol.NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(NewInvocationControlAssertionError.java:21)
at org.powermock.api.easymock.PowerMock.verifyClass(PowerMock.java:2279)
at org.powermock.api.easymock.PowerMock.verify(PowerMock.java:1646)
at MyTest.testServletUploadCreation(MyTest.java:21)
为什么?我该如何解决它?

请注意this way模拟构造函数在我的代码的其他地方工作。

最佳答案

看来您需要将此行 @PrepareForTest(ServletFileUpload.class) 更改为 @PrepareForTest(ClassBeingTested.class)

关于java - 如何使用 PowerMock 模拟 ServletFileUpload 的创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19181469/

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