You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MUnit 2.3.0中模拟error.muleMessage测试onError Propagate

解决方案:MUnit 2.3.0模拟带HTTP状态码的错误触发onError Propagate

你的核心问题是:普通Java Exception无法被Mule包装成包含error.muleMessage.attributes.statusCode的错误对象,而原Flow的on-error-propagate依赖该属性判断触发条件。正确的做法是模拟HTTP请求组件抛出的错误,因为原场景中错误来自http:request,这类错误天然包含状态码属性。

具体实现步骤

在MUnit测试用例中,通过munit-tools:mock-when拦截http:request组件,返回带有指定状态码的Mule错误对象,而非普通Java异常。

完整测试用例代码

<munit:test name="APIFlow-test" doc:id="f2d3a1b0-1234-4567-89ab-cdef01234567" description="测试触发onError Propagate的场景">
    <munit:behavior>
        <!-- 拦截目标HTTP请求组件 -->
        <munit-tools:mock-when processor="http:request" doc:name="Mock API Call" doc:id="a1b2c3d4-5678-90ab-cdef-0123456789ab">
            <munit-tools:with-attributes>
                <munit-tools:with-attribute name="doc:name" value="API Call"/>
            </munit-tools:with-attributes>
            <!-- 返回带状态码的错误 -->
            <munit-tools:then-return-error type="HTTP:UNPROCESSABLE_ENTITY">
                <!-- 设置错误的attributes,包含statusCode -->
                <munit-tools:attributes>
                    <![CDATA[#[output application/java
                    ---
                    {
                        statusCode: 422
                    }
                    ]]]>
                </munit-tools:attributes>
                <munit-tools:message>
                    <munit-tools:payload value="API请求返回422错误"/>
                </munit-tools:message>
            </munit-tools:then-return-error>
        </munit-tools:mock-when>
    </munit:behavior>

    <munit:execution>
        <!-- 执行待测试的Flow -->
        <flow-ref name="APIFlow" doc:name="调用APIFlow"/>
    </munit:execution>

    <munit:validation>
        <!-- 验证Failure变量被设置为true -->
        <munit-tools:assert-that expression="#[vars.Failure]" is="#[MunitTools::isTrue()]" doc:name="断言失败标记为true"/>
        <!-- 验证重试日志已输出 -->
        <munit-tools:assert-logged-message pattern="API call failed...Retrying" level="INFO" doc:name="断言重试日志存在"/>
    </munit:validation>
</munit:test>

关键说明

  1. 错误类型匹配:

    • 针对不同状态码,使用对应的HTTP错误类型:
      • 422 → HTTP:UNPROCESSABLE_ENTITY
      • 500 → HTTP:INTERNAL_SERVER_ERROR
      • 503 → HTTP:SERVICE_UNAVAILABLE
      • 504 → HTTP:GATEWAY_TIMEOUT
    • 若不想指定具体错误类型,可使用通用的ANY类型,但需确保错误对象包含statusCode属性。
  2. 为什么普通Exception不行:
    Java原生Exception不会被Mule封装为带有muleMessage属性的错误对象,只有Mule组件(如http:request)抛出的错误才会包含error.muleMessage.attributes这类上下文信息。

  3. 灵活扩展:
    若需要测试多个状态码场景,可复制mock-when块并修改statusCode和对应的错误类型即可。

内容的提问来源于stack exchange,提问作者VISHNU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:25:01