Search code examples
junitmockitopowermocktestcasepowermockito

Junit - Mocking static method


I'm writting a Junit test class "ServiceImplTest.java" for following method but its getting null, while trying Marshall xmlRequest. Can anybody help me out to resolve this issue please. Thanks in advance.

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

Note: Getting null value in below statement

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

Solution

  • You don't have defined your matchers correctly. Could you change it by:

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

    Import for Mockito any matcher, as follows:

    import static org.mockito.Matchers.any;
    

    Cheers