我如何使用 Munit Spy 在传出的 Mule 请求上断言 header

How can I assert a header on an outgoing Mule Request with an Munit Spy

我的 mule 流正在使用 http:request 组件发出传出的 http 请求。我正在使用 http:request-builder 将 header 添加到请求中。

    <http:request doc:name="unnamedImportApi"
        config-ref="HTTP_Request_Configuration"
        path="${outgoing.api.base_path}/import" method="POST">
        <http:request-builder>
            <http:header headerName="Authorization" value="Token token=#[flowVars['api_key']]"/>
        </http:request-builder>
    </http:request>

在编写测试时,我使用 MUnit 模拟和间谍来断言传出请求的内容。不过,我不确定如何在间谍中获取 headers 的值。例如。下面我想将 Authorization header 和 authHeader 存储在 spyData 中,但我不确定如何从 MuleMessage 获取 header。

       Map<String, String> spyData = new HashMap<>();
       spyMessageProcessor("request").ofNamespace("http")
        .withAttributes(attribute("path").withValue(apiPath))
        .before(new SpyProcess() {

            public void spy(MuleEvent event) throws MuleException {
                try {
                    spyData.put("payload", event.getMessage().getPayloadAsString());
                    spyData.put("contentType", ""+event.getMessage().getOutboundProperty("Content-type"));
                    spyData.put("method", ""+event.getMessage().getOutboundProperty("http.method"));
                    spyData.put("authHeader", ??????);
                } catch (Exception e) {
                    System.err.println("ERROR - Test Spy caused exception");
                    e.printStackTrace();
                    fail("Test Spy threw exception");
                }
            }
        });

将 headers 添加到 http 出站的另一种方法是使用 mule 消息设置出站属性。 使用表达式转换器设置您的 http header,http 出站端点将自动接收它。

在 MUnit 中,您可以将 eventContext 作为静态变量访问,使用它可以检索 mule 消息并设置或从中获取出站属性。

您好,不确定是否有办法满足您的需求。

你看看你是否像建议的那样,事先将 headers 设置为出站属性,然后你可以 运行 在 spy before 部分中断言并验证这些出站变量是那里。

但是如果你在 request-build 中定义它们,那时候 spy 运行s 那些 headers 还没有被定义。那是因为这些变量的定义发生在连接器内部,也发生在连接器之前或之后。

现在您可以尝试 运行 验证之后,但在这种情况下,您将处理一条消息,该消息是对您之前发送的请求的响应。所以不好。

就是说,我认为您希望确保您的消息按照您定义的方式发送出去。就像你在闻一样。我认为你至少不能以简单的方式做到这一点(即不是 hack 方式)。

不过我想提出一些不同的建议。您的生产代码是:

<http:request doc:name="unnamedImportApi"
        config-ref="HTTP_Request_Configuration"
        path="${outgoing.api.base_path}/import" method="POST">
        <http:request-builder>
            <http:header headerName="Authorization" value="Token token=#[flowVars['api_key']]"/>
        </http:request-builder>
    </http:request>

现在,您正在通过设置 #[flowVars[[=​​35=]]] 的值来构建您的 header 您可以通过执行以下操作在代码中检索该值:

spyData.put("authHeader", event.getMessage().getInvocationProperty("api_key"));

这应该足以验证,尽管您无法验证值 value="Token token= 的静态部分是否正确。这是 MUnit 应该改进的地方。

你应该相信,如果 request-build 人通过

这么说
<http:header headerName

您最终会设置 header,然后它应该会起作用。 就像相信您所依赖的 API 正常工作一样。所以你可以专注于测试你自己的代码。

HTH