Spring - Как создать тест junit для сервиса soap - PullRequest
0 голосов
/ 27 января 2020

Я следую весеннему руководству, чтобы создать привет мир soap ws. Ссылка ниже:

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

Ответы [ 2 ]

0 голосов
/ 26 марта 2020

если вы используете среду Spring ws для реализации ваших конечных точек, см. Spring-ws-test. вы найдете MockWebServiceClient, который издевается над клиентом и проверяет вашу конечную точку. Я предлагаю вам посмотреть этот пример: https://memorynotfound.com/spring-ws-server-side-integration-testing/

это работает только для весенних веб-сервисов, а не для веб-сервисов CXF.

0 голосов
/ 27 января 2020

Пожалуйста, измените метод GET на POST.

mockMvc.perform(

                postURI) // <-- This line!!!
                        .accept(MediaType.TEXT_XML)
                        .contentType(MediaType.TEXT_XML)
                        .content(request)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...