1
我试图了解如何使用Powermock。 我试图实现静态方法嘲讽here的例子。Powermock:NoClassDefFoundError尝试模拟静态类
我根据上面的例子创建了这段代码。
但是当我尝试运行测试时,我得到了一个NoClassDefFoundError。
我不知道到底是什么导致了这个错误,因为它主要是复制粘贴代码。
// imports redacted
@RunWith(PowerMockRunner.class)
@PrepareForTest(Static.class)
public class YourTestCase {
@Test
public void testMethodThatCallsStaticMethod() throws Exception {
// mock all the static methods in a class called "Static"
PowerMockito.mockStatic(Static.class);
// use Mockito to set up your expectation
PowerMockito.when(Static.class, "firstStaticMethod", any()).thenReturn(true);
PowerMockito.when(Static.class, "secondStaticMethod", any()).thenReturn(321);
// execute your test
new ClassCallStaticMethodObj().execute();
// Different from Mockito, always use PowerMockito.verifyStatic() first
// to start verifying behavior
PowerMockito.verifyStatic(Mockito.times(2));
// IMPORTANT: Call the static method you want to verify
Static.firstStaticMethod(anyInt());
// IMPORTANT: You need to call verifyStatic() per method verification,
// so call verifyStatic() again
PowerMockito.verifyStatic(); // default times is once
// Again call the static method which is being verified
Static.secondStaticMethod();
// Again, remember to call verifyStatic()
PowerMockito.verifyStatic(Mockito.never());
// And again call the static method.
Static.thirdStaticMethod();
}
}
class Static {
public static boolean firstStaticMethod(int foo) {
return true;
}
public static int secondStaticMethod() {
return 123;
}
public static void thirdStaticMethod() {
}
}
class ClassCallStaticMethodObj {
public void execute() {
boolean foo = Static.firstStaticMethod(2);
int bar = Static.secondStaticMethod();
}
}
可悲的是没有解决的NoClassDefFoundError错误。 – Philippe
你的classpath是如何设置的? – 2017-04-19 09:57:43
'NoClassDefFoundError'堆栈跟踪是否显示缺少的类? – 2017-04-19 11:48:08