Spring - 如何为SOAP服务构建一个Junit测试

3
我在按照Spring指南创建"hello world" SOAP Web服务。下面是链接:https://spring.io/guides/gs/producing-web-service/ 我已经成功地实现了它。当我运行以下命令行时:

curl --header "content-type: text/xml" -d @src/test/resources/request.xml http://localhost:8080/ws/coutries.wsdl

我会得到这个响应。
<SOAP-ENV:Header/><SOAP-ENV:Body><ns2:getCountryResponse xmlns:ns2="http://spring.io/guides/gs-producing-web-service"><ns2:country><ns2:name>Spain</ns2:name><ns2:population>46704314</ns2:population><ns2:capital>Madrid</ns2:capital><ns2:currency>EUR</ns2:currency></ns2:country></ns2:getCountryResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>

现在我正在尝试为这个服务(控制器层)创建一个JUnit测试,但它无法正常工作。

这是我的单元测试:

@RunWith(SpringRunner.class)
@WebMvcTest(CountryEndpoint.class)
@ContextConfiguration(classes = {CountryRepository.class, WebServiceConfig.class})
public class CountryEndpointTest {

    private final String URI = "http://localhost:8080/ws/countries.wsdl";

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {


        mockMvc.perform(

                get(URI)
                        .accept(MediaType.TEXT_XML)
                        .contentType(MediaType.TEXT_XML)
                        .content(request)

        )
                .andDo(print())
                .andExpect(status().isOk());
    }

    static String request = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
            "                  xmlns:gs=\"http://spring.io/guides/gs-producing-web-service\">\n" +
            "    <soapenv:Header/>\n" +
            "    <soapenv:Body>\n" +
            "        <gs:getCountryRequest>\n" +
            "            <gs:name>Spain</gs:name>\n" +
            "        </gs:getCountryRequest>\n" +
            "    </soapenv:Body>\n" +
            "</soapenv:Envelope>";
}

这里出现了错误:

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :200
Actual   :404

我把日志级别改成了调试模式,并发现了以下内容:

2020-01-27 18:04:11.880  INFO 32723 --- [           main] c.s.t.e.s.endpoint.CountryEndpointTest   : Started CountryEndpointTest in 1.295 seconds (JVM running for 1.686)
2020-01-27 18:04:11.925 DEBUG 32723 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /ws/countries.wsdl
2020-01-27 18:04:11.929 DEBUG 32723 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/ws/countries.wsdl]
2020-01-27 18:04:11.930 DEBUG 32723 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/ws/countries.wsdl] are [/**]
2020-01-27 18:04:11.930 DEBUG 32723 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/ws/countries.wsdl] are {}
2020-01-27 18:04:11.931 DEBUG 32723 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/ws/countries.wsdl] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@c7a977f]]] and 1 interceptor

我尝试了另一种解决方案(如下),但它也不起作用。

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {WebServiceConfig.class, CountryRepository.class})
public class CountryEndpointTest {

    private final String URI = "http://localhost:8080/ws/countries.wsdl";

    private MockMvc mockMvc;

    @Autowired
    CountryRepository countryRepository;


    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(new CountryEndpoint(countryRepository)).build();
    }
3个回答

4

Spring文档表示:

https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/html/boot-features-testing.html

默认情况下,@SpringBootTest不会启动服务器。

您需要定义:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 

运行服务器。

我尝试使用mockserver,但无法访问端点(即使使用WebEnvironment.DEFINED_PORT)。

因此,我按照以下步骤进行:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class FacturationEndpointTest {

@Autowired
private WebTestClient webClient;

@Test
public void testWSDL() throws Exception {

    this.webClient.get().uri("/test_service/services.wsdl")
            .exchange().expectStatus().isOk();

}

如果您想像我这样使用WebTestClient,您需要在您的pom.xml中添加以下依赖项:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <scope>test</scope>
</dependency>

它就像魔法一样!!!我必须升级我的Spring Boot版本(我目前使用的是1.X.X版本)以使用Webflux。感谢@bastien的评论和解决方案。 - Amdouni Mohamed Ali

1

1
感谢Badreddine的回复。不幸的是,这个例子在我的情况下无法工作,因为我正在使用更新版本的Spring Boot(1.5.6.RELEASE),但是这个例子使用了一个已弃用的版本(https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-ws?repo=springio-plugins-release)。 - Amdouni Mohamed Ali
另一个解决方案可能是使用 RestAssured 框架,请参考用法:https://github.com/rest-assured/rest-assured/wiki/Usage - BOUZEL Badreddine

0
请将 GET 方法更改为 POST
mockMvc.perform(

                postURI) // <-- This line!!!
                        .accept(MediaType.TEXT_XML)
                        .contentType(MediaType.TEXT_XML)
                        .content(request)

我已经更改了它,但似乎没有解决问题。我的状态显示404。 - Amdouni Mohamed Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接