Search code examples
spring-wsspring-junitspringjunit4classrunnerwebservicetemplate

JUnit for Spring WebServiceTemplate not working


I am consuming a SOAP Webservice using Spring WebServiceTemplate. While executing the JUnit I am facing an issue.

My Client class:

@Service
public class MyWsClient extends WebServiceGatewaySupport {

@Autowired
private WebServiceTemplate webServiceTemplate;

public String getData(...) throws Exception{
    ...
    SampleResponse response = (SampleResponse) webServiceTemplate.marshalSendAndReceive(request);
    ...
    return response.getData();
}}

My Test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext-junit.xml"})
public class MyWsClientTest {

@Autowired
ApplicationContext applicationContext;

@InjectMocks
MyWsClient myWsClient;

private MockWebServiceServer mockServer;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    mockServer = MockWebServiceServer.createServer(applicationContext);
}

@Test
public void testGetData() throws Exception {

    Source expectedRequestPayload = new StringSource(
            "<customerCountRequest xmlns=\"http://springframework.org/spring-ws/test\" />");
    Source responsePayload = new StringSource(
            "<customerCountResponse xmlns='http://springframework.org/spring-ws/test'>"
                    + "<customerCount>10</customerCount>" + "</customerCountResponse>");
    mockServer.expect(RequestMatchers.payload(expectedRequestPayload)).andRespond(ResponseCreators.withPayload(responsePayload));

    String data = myWsClient.getData(...);
    assertNotNull(data);
    mockServer.verify();
}}

Issue:
When i execute my test case I am getting NullPointerException for line "webServiceTemplate.marshalSendAndReceive(request)" inside my Client class.
The webServiceTemplate is coming as null.
Any idea what I am doing wrong?


Solution

  • I resolved it by changing the @InjectMocks to @Autowired on the "MyWsClient myWsClient";