注入模拟Spring WebServiceTemplate以返回预定义的值

时间:2018-01-25 14:35:09

标签: spring web-services

我们的网络服务最终更新。我使用Spring Web服务更新了客户端代码。

问题是单元测试在返回时失败,因为注入的模拟WebServiceTemplate返回null。

我的问题是“有没有办法让返回一些预定值?”

@Configuration
public class TestConfig {
    @Bean
    public WebServiceTemplate webServiceTemplate() {
        WebServiceTemplate webServiceTemplate = mock(WebServiceTemplate.class);
        return webServiceTemplate;
    }

    @Bean
    public TheServiceClient client() {
        return new TheServiceClient();
    }

}

public class TheServiceClient {
    @Autowired
    private WebServiceTemplate webServiceTemplate;

    public TheResponse getResponse(TheRequest request) {
        // logic handles the request need to be tested
        JAXBElement<?> element = (JAXBElement<?>) webServiceTemplate.marshalSendAndReceive(request);
        return element.getResponse();
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class IdalClientTest {
    @Autowired
    private TheServiceClient client;

    @Test
    public void testGetResponse() {
        TheRequest request = new TheRequest();
        request.setters();

        TheResponse response = client.getResponse(request);
        assertThat(response.getSucess()).isTrue();
    }
}

1 个答案:

答案 0 :(得分:1)

因为您没有将模拟的WebServiceTemplate注入到TheServiceClient中 你应该这样做

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class IdalClientTest {

    @InjectMocks
    private TheServiceClient client;

    @Mock
    WebServiceTemplate webServiceTemplate;

    @Mock
    JAXBElement jaxBElement;

    @Before
     public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(webServiceTemplate.marshalSendAndReceive(any(TheRequest.class))).thenReturn(jaxBElement);
     // You can create a TheResponse object with success = true;          
   when(jaxBElement.getResponse()).thenReturn(dummyTheResponseObject);

    }
    @Test
    public void testGetResponse() {
        TheRequest request = new TheRequest();
        request.setters();

        TheResponse response = client.getResponse(request);
        assertThat(response.getSucess()).isTrue();
    }
}

您不需要该Configuration类。

使用构造函数注入而不是Field Injection的理想方法。喜欢这个

public class TheServiceClient {

private final WebServiceTemplate webServiceTemplate;

@Autowired
public TheServiceClient(final WebServiceTemplate webServiceTemplate) {
    this.webServiceTemplate = webServiceTemplate;  
 }
    .......
}

然后在你的测试类而不是InjectMocks中你可以这样做

private TheServiceClient client;

@Mock
WebServiceTemplate webServiceTemplate;


@Before
 public void setUp() {
    MockitoAnnotations.initMocks(this);
    client = new TheServiceClient(webServiceTemplate);
       .............
}
 ................