Junit - 模拟静态方法

Junit - Mocking static method

我正在为以下方法编写 Junit 测试 class“ServiceImplTest.java”,但它在尝试 Marshall xmlRequest 时变为空。 谁能帮我解决这个问题。提前致谢。

ServiceImplTest.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({RequestXmlBuilder.class})
public class ServiceImplTest {
    @Before
    public void setUp() throws Exception {
       PowerMockito.mockStatic(RequestXmlBuilder.class);
    }

    @Test
    public void testExecute() throws Exception {
       PowerMockito.when(RequestXmlBuilder.serviceMarshall(Request, jaxb2Marshaller)).thenReturn("XmlTest");
    }
}

ServiceImpl.java

public class ServiceImpl {
    public Response execute() {
        String xmlRqst = RequestXmlBuilder.serviceMarshall(request, jaxb2Marshaller);
    }
}

RequestXmlBuilder.java

public class RequestXmlBuilder {
    public static String serviceMarshall(Request request, Jaxb2Marshaller jaxb2Marshaller)
            throws JAXBException {
        StringWriter requestXml = new StringWriter();
        jaxb2Marshaller.marshal(request, new StreamResult(requestXml));
        return requestXml.toString();
    }
}

注意:在下面的语句中获取空值

jaxb2Marshaller.marshal(request, new StreamResult(requestXml));

您没有正确定义 matchers。您可以通过以下方式更改它:

PowerMockito.when(RequestXmlBuilder.serviceMarshall(any(Request.class), any(Jaxb2Marshaller.class))).thenReturn("XmlTest");

为Mockito导入任意匹配器,如下:

import static org.mockito.Matchers.any;

干杯