Копируйте сообщение из сторонней системы в Mule, используя MUnit
Я пишу набор тестов (использующий Munit) для приложения Mule, которое обрабатывает новые данные, поступающие из экземпляра Magento. Один из моих потоков - опрос Magento для новых клиентов, и полученное сообщение имеет тип: com.magento.api.CustomerCustomerEntity
Мне интересно, как я мог бы посмеяться над этим, чтобы в моем тестовом случае, когда вызывался процессор сообщений Magento, я мог вернуть полезную нагрузку того же типа и сделать соответствующие утверждения?
В настоящее время мой тест Munit выглядит следующим образом:
<mock:config name="mock_MagentoToSalesforce" doc:name="Mock configuration"/>
<spring:beans>
<spring:import resource="classpath:MagentoToSalesforce.xml"/>
<spring:bean id="myBean" name="myBean" class="com.magento.api.CustomerCustomerEntity">
<spring:property name="email" value="test@test.com"/>
</spring:bean>
</spring:beans>
<munit:test name="MagentoToSalesforce-test-getCustomersFlowTest" description="Test">
<mock:when config-ref="mock_MagentoToSalesforce" messageProcessor=".*:.*" doc:name="Mock">
<mock:with-attributes>
<mock:with-attribute whereValue-ref="#[string:Get New Customers]" name="doc:name"/>
</mock:with-attributes>
<mock:then-return payload-ref="#[app.registry.myBean]"/>
</mock:when>
<flow-ref name="getCustomers" doc:name="Flow-ref to getCustomers"/>
</munit:test>
И поток я пытаюсь проверить это:
<flow name="getCustomers" processingStrategy="synchronous">
<poll doc:name="Poll">
<fixed-frequency-scheduler frequency="30" timeUnit="SECONDS"/>
<watermark variable="watermark" default-expression="#[new org.mule.el.datetime.DateTime().plusYears(-30)]" update-expression="#[new org.mule.el.datetime.DateTime().plusYears(-0)]" selector-expression="#[new org.mule.el.datetime.DateTime(payload.created_at, 'yyyy-MM-dd HH:mm:ss')]"/>
<magento:list-customers config-ref="Magento" filter="dsql:SELECT confirmation,created_at,created_in,customer_id,dob,email,firstname,group_id,increment_id,lastname,middlename,password_hash,prefix,store_id,suffix,taxvat,updated_at,website_id FROM CustomerCustomerEntity WHERE updated_at > '#[flowVars.watermark]'" doc:name="Get New Customers"/>
</poll>
<foreach doc:name="For Each">
<data-mapper:transform config-ref="MagentoCustomer_To_SalesforceContact" doc:name="Map Customer to SFDC Contact">
<data-mapper:input-arguments>
<data-mapper:input-argument key="ContactSource">Magento</data-mapper:input-argument>
</data-mapper:input-arguments>
</data-mapper:transform>
<flow-ref name="upsertSalesforceContactFlow" doc:name="upsertSalesforceContactFlow"/>
</foreach>
</flow>
Обновите после ответа Райана:
Изменено выражение для возврата полезной нагрузки #[ent = new com.magento.api.CustomerCustomerEntity(); ent.setEmail('test@test.com'); return [ent];]
- обратите внимание, изменил метод на setEmail
чтобы соответствовать документации здесь. Ошибка, которую я получаю с этим:
ERROR 2015-06-22 09:58:34,719 [main] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Object "org.mule.transport.NullPayload" not of correct type. It must be of type "{interface java.lang.Iterable,interface java.util.Iterator,interface org.mule.routing.MessageSequence,interface java.util.Collection}" (java.lang.IllegalArgumentException). Message payload is of type: NullPayload
Code : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. Object "org.mule.transport.NullPayload" not of correct type. It must be of type "{interface java.lang.Iterable,interface java.util.Iterator,interface org.mule.routing.MessageSequence,interface java.util.Collection}" (java.lang.IllegalArgumentException)
org.mule.util.collection.EventToMessageSequenceSplittingStrategy:64 (null)
2. Object "org.mule.transport.NullPayload" not of correct type. It must be of type "{interface java.lang.Iterable,interface java.util.Iterator,interface org.mule.routing.MessageSequence,interface java.util.Collection}" (java.lang.IllegalArgumentException). Message payload is of type: NullPayload (org.mule.api.MessagingException)
org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor:32 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.lang.IllegalArgumentException: Object "org.mule.transport.NullPayload" not of correct type. It must be of type "{interface java.lang.Iterable,interface java.util.Iterator,interface org.mule.routing.MessageSequence,interface java.util.Collection}"
at org.mule.util.collection.EventToMessageSequenceSplittingStrategy.split(EventToMessageSequenceSplittingStrategy.java:64)
at org.mule.util.collection.EventToMessageSequenceSplittingStrategy.split(EventToMessageSequenceSplittingStrategy.java:25)
at org.mule.routing.CollectionSplitter.splitMessageIntoSequence(CollectionSplitter.java:29)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
1 ответ
Один из способов - создать объект самостоятельно, используя конструктор или свойства / установщики.
Из документов: http://mulesoft.github.io/magento-connector/2.1.2/java/com/magento/api/CustomerCustomerEntity.html
<mock:then-return payload-ref="#[ent = new com.magento.api.CustomerCustomerEntity(); ent.email('test@test.com'); return ent;]"/>
Вы также можете создавать эти объекты как многоразовые пружинные бобы и ссылаться на них из MEL.
<bean class="com.magento.api.CustomerCustomerEntity" id="myEntityWithEmail">
<property name="email" value="test@test.com" />
</bean>
<mock:then-return payload-ref="#[app.registry.myEntityWithEmail]"/>
После вашего обновления я вижу, что вы используете foreach, который ожидает коллекцию или итерацию. Вы можете вернуть коллекцию пользовательских объектов просто в MEL, используя: [], например:
#[ent = new com.magento.api.CustomerCustomerEntity(); ent.email('test@test.com'); return [ent];]
Больше о MEL здесь: https://developer.mulesoft.com/docs/display/current/Mule+Expression+Language+MEL
Или снова вы можете использовать Spring, чтобы вернуть список:
<util:list id="entities">
<ref bean="myEntityWithEmail" />
</util:list>