本文介绍了通过whennew()的powermock模拟构造函数不适用于匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DummyResource 类和一个 DummyTarget 文件,以及一个测试类 TestDummyResource,如下所示,但模拟对象 DummyResource dr = mock(DummyResource.class) 仅在我在普通类,当在匿名类中调用时,它调用的是实际的构造函数,而不是使用模拟对象.

I have a DummyResource class and a DummyTarget file, and a test class TestDummyResource as below, but the mocked object DummyResource dr = mock(DummyResource.class) only works when I call the constructor inside a normal class, when it's called in an anonymous class, it's calling the actual constructor instead of using the mocked object.

版本:

powermock 1.4.12 mockito 1.9.0 junit 4.8.2

powermock 1.4.12 mockito 1.9.0 junit 4.8.2

DummyTarget.java:

import java.io.IOException;
import java.io.OutputStream;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;


public class DummyTarget {
    public StreamingOutput testMocking() {
        return new StreamingOutput() {
            @Override
            public void write(OutputStream arg0) throws IOException, WebApplicationException {
                new DummyResource();
            }
        };
    }
}

DummyResource.java:

package com.smin.dummy;

public class DummyResource {
    public DummyResource() {
        System.out.println("mock failure");
    }
}

TestDummyResource.java:

package com.smin.dummy;

import static org.mockito.Mockito.mock;

import java.io.IOException;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({DummyResource.class,DummyTarget.class})
public class TestDummyResource  {

    @Before
    public void setUp() throws Exception {
        DummyResource dr = mock(DummyResource.class);
        PowerMockito.whenNew(DummyResource.class).withNoArguments().thenReturn(dr);
    }

    @Test
    public void testMocked() throws WebApplicationException, IOException {
        new DummyResource(); // it uses the mocked object dr here,
                             //doesn't print "mock failure"
        StreamingOutput sop = new DummyTarget().testMocking();
        sop.write(null);     // it calls DummyResource's constructor,
                             // prints ""mock failure"" here
    }
}

推荐答案

看起来匿名类可能会继承定义它的类的包.你能试试 PrepareForTest?:

It looks like an anonymous class may inherit the package of the class that defines it. Can you try the wildcard form of PrepareForTest?:

@PrepareForTest("com.smin.dummy.*")

如果这不起作用,您可以尝试霰弹枪 PrepareEverythingForTest 注释.

If that doesn't work, you could try the shotgun PrepareEverythingForTest Annotation.

这篇关于通过whennew()的powermock模拟构造函数不适用于匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 12:57