powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Тестирование jax-ws веб сервиса
3 сообщений из 3, страница 1 из 1
Тестирование jax-ws веб сервиса
    #38322930
abc_da
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Добрый день,
Хочу написать unit-тест для кода, который обрабатывает ответы jax-ws веб сервиса. Использовать реальный сервис по разным причинам не получится, встал вопрос о mock-реализации. Через soapUI я собрал ответы реального сервиса, они довольно большие и мне не хотелось бы инициализировать эти объекты вручную. Подскажите, пожалуйста, могу ли я в своих тестах как-то инициализировать объекты, возвращаемые сервисом на базе xml-файлов с soap-конвертами?
...
Рейтинг: 0 / 0
Тестирование jax-ws веб сервиса
    #38322959
abc_da
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Кажется, это мне поможет.
...
Рейтинг: 0 / 0
Тестирование jax-ws веб сервиса
    #38323010
забыл ник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
abc_da,

Буквально неделю назад делал для spring-ws, выкладываю код - может поможет.

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
public class AIAControllerSpecParent{

	@Before
	public void setupData() {
		
		MockWebService.mockFactory();
		MockWebService.map(UsageEligibilityRequest.class, "discovery/aia/services/mock/xml/common/UsageEligibilityResponse.xml");
		MockWebService.map(GetUsageRequest.class, "discovery/aia/services/mock/xml/common/GetUsageResponse.xml");
		MockWebService.map(RetrieveTenantIdRequest.class, "discovery/aia/services/mock/xml/common/RetrieveTenant.xml");
	}



Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;

import org.springframework.ws.client.core.WebServiceTemplate;

@SuppressWarnings("rawtypes")
public class MockWebService {

	private static Map<Class<?>, String> responseMapping = new HashMap<Class<?>, String>();
	private static Map<Class<?>, MockWebServiceConnectionHandler> handlersMapping = new HashMap<Class<?>, MockWebServiceConnectionHandler>(); 

	public static void map(Class<?> payloadClass, String resourcePath) {
		responseMapping.put(payloadClass, resourcePath);
	}
	
	public static void addHandler(MockWebServiceConnectionHandler handler) {
		ParameterizedType type =(ParameterizedType) handler.getClass().getGenericSuperclass();
		Class<?> commandClass = (Class<?>) type.getActualTypeArguments()[0];
		handlersMapping.put(commandClass, handler);
	}

	public static String getResourcePath(Class<?> payloadClass) {
		return responseMapping.get(payloadClass);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> MockWebServiceConnectionHandler<T> getHandler(Class<T> payloadClass) {
		return handlersMapping.get(payloadClass);
	}

	public static void mockFactory() {
		
		clearMapping();
		
		Map<String, WebServiceTemplate> all = WebServiceTemplateFactory.getContext().getBeansOfType(WebServiceTemplate.class);

		for (WebServiceTemplate t : all.values()) {
			t.setMessageSender(new FileWebServiceMessageSender(t));
		}

	}
	
	static void clearMapping() {
		responseMapping.clear();
		handlersMapping.clear();
	}

}



Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ws.client.core.WebServiceTemplate;

public class WebServiceTemplateFactory {
	
	final ClassPathXmlApplicationContext context;
	
	private WebServiceTemplateFactory() {
		context = new ClassPathXmlApplicationContext("integration-service-context.xml");
	}
	
	private static final WebServiceTemplateFactory instance = new WebServiceTemplateFactory();
	
	public static WebServiceTemplate getTemplate(String bean) {
		return (WebServiceTemplate)WebServiceTemplateFactory.instance.context.getBean(bean);
	}
	
	public static ApplicationContext getContext() {
		return instance.context;
	}

}



Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
import java.io.IOException;

public abstract class MockWebServiceConnectionHandler<T> {
	
	public void send(T t) throws IOException {
		
	}
	
	public String getReponsePath(T t) {
		return null;
	}
	
	protected void refuseConnection() throws IOException {
		throw new IOException("Connection refused");
	}
	

}



Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.springframework.oxm.Unmarshaller;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.soap.saaj.SaajSoapMessageFactory;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageSender;

public class FileWebServiceMessageSender implements WebServiceMessageSender {

	static final SaajSoapMessageFactory FACTORY = new SaajSoapMessageFactory();

	static {
		FACTORY.afterPropertiesSet();
	}
	
	Unmarshaller unmarshaller;
	
	public FileWebServiceMessageSender(WebServiceTemplate t) {
		unmarshaller = t.getUnmarshaller();
	}
	

	public WebServiceConnection createConnection(final URI uri) throws IOException {

		return new WebServiceConnection() {
			
			Object request = null;
			@SuppressWarnings("rawtypes")
			MockWebServiceConnectionHandler handler = null;
			
			
			@SuppressWarnings({ "unchecked"})
			public void send(WebServiceMessage message) throws IOException {
				
				request = unmarshaller.unmarshal(message.getPayloadSource());
				
				handler = MockWebService.getHandler(request.getClass());
						
				if (handler != null) {
					handler.send(request);
				}

			}

			@SuppressWarnings("unchecked")
			public WebServiceMessage receive(WebServiceMessageFactory messageFactory) throws IOException {
				
				String responsePath = MockWebService.getResourcePath(request.getClass());
				
				if (handler != null && handler.getReponsePath(request) != null) {
					responsePath = handler.getReponsePath(request);
				}
				
				if (responsePath == null) {
					throw new NullPointerException("Response path is not specified for request " + request.getClass());
				}

				return FACTORY.createWebServiceMessage(getClass().getClassLoader().getResourceAsStream(responsePath));
			}

			public boolean hasError() throws IOException {
				return false;
			}

			public URI getUri() throws URISyntaxException {
				return null;
			}

			public String getErrorMessage() throws IOException {
				return null;
			}

			public void close() throws IOException {

			}
		};
	}

	public boolean supports(URI uri) {
		return true;
	}
}



Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">


	<bean id="wsMessageSender"
		class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
		<property name="connectionTimeout" value="60000" />
		<property name="readTimeout" value="120000" />
		<property name="maxTotalConnections" value="10000" />
	</bean>

	<!-- Usage service -->

	<bean id="usageServiceMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
		<property name="contextPath" value="za.co.discovery.vitality.usageservice" />
	</bean>

	<bean id="usageServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
		<property name="marshaller" ref="usageServiceMarshaller" />
		<property name="unmarshaller" ref="usageServiceMarshaller" />
		<property name="defaultUri" value="${usage.service.URL}" />
		<property name="messageSender" ref="wsMessageSender" />
	</bean>


</beans>
...
Рейтинг: 0 / 0
3 сообщений из 3, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Тестирование jax-ws веб сервиса
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]