本文介绍了无法在Spring Boot项目中使用SpringJUnit4ClassRunner运行powermockrule的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Spring Boot项目,需要使用spring testRunner进行测试(这样我才能获得真实的应用程序上下文)并模拟静态方法。
I have a spring boot project that needs to test with spring test runner(so that I can get the real application context) and mock the static method.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes= MyApplication.class)
@PrepareForTest(StaticClass.class)
public class StaticClassTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
@Autowired
HelloCmd hello;
@Test
public void testGetOne() {
mockStatic(StaticClass.class);
when(StaticClass.getNumber()).thenReturn(2);
System.out.println(hello.getNumber());
}
}
运行测试时,我收到以下错误消息:
And I got following error message when run the test:
com.thoughtworks.xstream.converters.ConversionException: hello.hystrix.commands.HelloCmd$$EnhancerBySpringCGLIB$$a27be1be : hello.hystrix.commands.HelloCmd$$EnhancerBySpringCGLIB$$a27be1be
---- Debugging information ----
message : hello.hystrix.commands.HelloCmd$$EnhancerBySpringCGLIB$$a27be1be
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message : hello.hystrix.commands.HelloCmd$$EnhancerBySpringCGLIB$$a27be1be
class : hello.hystrix.commands.StaticClassTest
required-type : hello.hystrix.commands.StaticClassTest
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /org.powermock.modules.junit4.rule.PowerMockStatement$1/outer-class/fNext/next/next/target/hello
line number : 15
class[1] : org.junit.internal.runners.statements.InvokeMethod
class[2] : org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks
class[3] : org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks
class[4] : org.powermock.modules.junit4.rule.PowerMockStatement
class[5] : org.powermock.modules.junit4.rule.PowerMockStatement$1
version : null
如何解决此问题?谢谢!
How to fix this? Thanks!
推荐答案
我从这里
以使用PowerMockRunnerDelegate代替PowerMockRule。
I found a fix from here linkto use PowerMockRunnerDelegate instead of PowerMockRule.
更新后的测试类为:
The updated test class would be:
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes= MyApplication.class)
@PrepareForTest(StaticClass.class)
public class StaticClassTest {
@Autowired
HelloCmd hello;
@Test
public void testGetOne() {
mockStatic(StaticClass.class);
when(StaticClass.getNumber()).thenReturn(2);
System.out.println(hello.getNumber());
}
}
这篇关于无法在Spring Boot项目中使用SpringJUnit4ClassRunner运行powermockrule的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!