无法使用PowerMockRule为final类创建子类

时间:2016-03-28 18:19:37

标签: java mockito powermock powermockito eclemma

我使用JUNIT和Powermockito以及EclEmma来测试我的代码。现在有一个问题。我必须测试这个类:

<div class="npr-import-media npr-import-audio npr-import-images" id="media-container">

    <div class="npr-import-media-container" draggable="true">
        <audio src="<?php echo $audio->format->mp4->{'$text'}; ?>" controls></audio>
        <span class="npr-media-delete">X</span>
    </div>

    <div class="npr-import-image-container npr-import-media-container" draggable="true">
        <img class="npr-import-image" src="<?php echo $image->src; ?>" >
        <span class="npr-import-image-caption"><?php echo $image->caption->{'$text'} ?></span>
        <span class="npr-media-delete">X</span>
    </div>

    <div class="npr-import-add-media npr-import-media-container">
        Add Media+
    </div>

</div>

这是我的测试:

public class Main
{
    private static final Logger slf4jLogger = LoggerFactory.getLogger(Main.class);
    private static final Marker marker      = MarkerFactory.getMarker("Test");

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        System.out.println(slf4jLogger);
        slf4jLogger.debug(marker, "Hallo");
        slf4jLogger.trace(marker, "Hallo");
        slf4jLogger.info(marker, "Hallo");
        slf4jLogger.warn(marker, "Hallo");
        slf4jLogger.error(marker, "Hallo");
    }

}

但是有以下错误:

  

java.lang.IllegalArgumentException:不能继承最终类类   org.slf4j.LoggerFactory at   org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:447)at at   org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)     在   org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)     在org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)     在org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)     在   org.powermock.api.mockito.repackaged.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)     在   org.powermock.api.mockito.repackaged.ClassImposterizer.imposterise(ClassImposterizer.java:57)     在   org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)     在   org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:59)     在   org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:70)   ...

我不想要powermock-module-javaagent。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

一种选择是为slf4jLogger创建静态getter方法,然后重构您的main方法以调用此新方法。然后,您可以在测试中存根此方法:

PowerMockito.spy(Main.class);
PowerMockito.when(Main.getSlf4jlogger()).thenReturn(logger);

(而不是

PowerMockito.mockStatic(LoggerFactory.class);
PowerMockito.when(LoggerFactory.getLogger(Mockito.any(Class.class))).thenReturn(logger);