春季-如何为肥皂服务构建junit测试

时间:2020-01-27 17:11:09

标签: spring-boot spring-mvc junit spring-test-mvc

我正在按照春季指南创建一个世界级的肥皂ws。下面的链接:

https://spring.io/guides/gs/producing-web-service/

我成功地使它工作了。当我运行此命令行时:

curl --header“内容类型: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 个答案:

答案 0 :(得分:2)

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) 

运行服务器。

我尝试使用模拟服务器,但无法访问端点(即使使用 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>

答案 1 :(得分:0)

请将GET方法更改为POST

mockMvc.perform(

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

答案 2 :(得分:0)

如果您正在使用spring ws框架来实现端点,请参阅spring-ws-test。您将找到一个模拟客户端并测试您的端点的MockWebServiceClient。我建议您看这个例子:https://memorynotfound.com/spring-ws-server-side-integration-testing/

这仅适用于spring Web服务,不适用于CXF Web服务。