当前位置:  开发笔记 > 编程语言 > 正文

无法在Spring启动项目中使用SpringJUnit4ClassRunner运行powermockrule

如何解决《无法在Spring启动项目中使用SpringJUnit4ClassRunner运行powermockrule》经验,为你挑选了1个好方法。

我有一个spring boot项目,需要使用spring test runner进行测试(以便我可以获得真正的应用程序上下文)并模拟静态方法.

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

运行测试时出现以下错误消息:

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

如何解决这个问题?谢谢!



1> snowery..:

我从这里找到了一个修复链接 ,使用PowerMockRunnerDelegate而不是PowerMockRule.

更新的测试类将是:

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

推荐阅读
无名有名我无名_593
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有