当前位置: 首页 > 知识库问答 >
问题:

Camel单元测试总是失败,我无法解释为什么期望是0或者如何正确地断言期望

沈飞跃
2023-03-14

我有这个带有Apache Camel的Restendpoint来查找来自不同来源的一些值,首先我验证请求,然后根据路径我去不同的路由:

restConfiguration()
    .component("servlet")
    .bindingMode(RestBindingMode.json)
...

rest("/lookup/{path}")
    .consumes(MediaType.APPLICATION_JSON_VALUE)
    .produces(MediaType.APPLICATION_JSON_VALUE)
    .post().type(LookupRequest.class).outType(LookupResponse.class)
    .to("direct:validate-request")

from("direct:validate-request")
    .routeId(Constants.ROUTE_VALIDATE_REQUEST)
    .to("bean-validator://x")
    .process(exchange ->
        exchange.getIn().setHeader("lookupType", env.getProperty("lookup.path." + exchange.getIn().getHeader("path", String.class)))
    )
    .to("bean:lookupValidationService?method=validate(${body}, ${header.lookupType})")
    .toD("direct:db-lookup-${header.lookupType}");

from("direct:db-lookup-customer")
    .routeId(Constants.ROUTE_CUSTOMER_LOOKUP)
    .log(LoggingLevel.DEBUG, CamelRouter.CAMEL_BODY)
        ...
    .to("sql:{{lookup.queries.customer}}?placeholder=~&usePlaceholder=true")
    .process(new SqlQueryResultProcessor())
        ...
    .endRest();

这是我测试路线的一次尝试:

@ActiveProfiles("test")
@CamelSpringBootTest
@SpringBootTest(classes = LookupServiceApplication.class)
@MockEndpointsAndSkip("log:.*")
@UseAdviceWith
class CameltestingApplicationTests {

    @Autowired CamelContext camelContext;
    @Autowired ProducerTemplate producerTemplate;

    @EndpointInject("mock:direct:db-lookup-customer")
    MockEndpoint customerMock;

    static List<Map<String, Object>> results = new ArrayList<Map<String, Object>>() {{
        add(new HashMap<String, Object>() {{
            put("customerName", "Test customer");
        }});
    }};

    @BeforeEach
    public void before() throws Exception {
        camelContext.setTracing(true);
        AdviceWith.adviceWith(camelContext, Constants.ROUTE_CUSTOMER_LOOKUP, routeBuilder -> {
            routeBuilder.interceptSendToEndpoint("sql:*").skipSendToOriginalEndpoint().process(e -> e.getIn().setBody(results));
        });
    }
    @Test
    public void testReceive() throws Exception {
        camelContext.start();
        // Expect:
        customerMock.expectedMessageCount(1);
        // And: the process to set the header
        customerMock.expectedHeaderReceived("lookupType", "customer.info");

        Map<String, Object> headers = new HashMap<>();
        headers.put("path", "customer.info");
        Map<String, Object> keywords = new HashMap<>();
        keywords.put("customerNumber", 1234678);
        LookupRequest request = new LookupRequest();
        request.setKeywords(keywords);

        // When we send the message
        producerTemplate.sendBodyAndHeaders("direct:validate-request", request, headers);
        // Everything is satisfied.
        Assert.assertNotNull(camelContext.hasEndpoint("direct:db-lookup-customer"));
        customerMock.assertIsSatisfied();
    }
}

这是日志:

2021-07-12 12:10:13.604  INFO 660 --- [           main] o.a.c.i.e.AbstractCamelContext           : Apache Camel 3.11.0 (Lookup service) started in 1s246ms (build:160ms init:1s7ms start:79ms)
2021-07-12 12:10:13.623  INFO 660 --- [           main] o.a.c.Tracing                            : *--> [validate    ] [from[direct:validate-request]    ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.624  INFO 660 --- [           main] o.a.c.Tracing                            :      [validate    ] [bean-validator://x               ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.727  INFO 660 --- [           main] o.a.c.Tracing                            :      [validate    ] [Processor@0x166ddfb7             ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.728  INFO 660 --- [           main] o.a.c.Tracing                            :      [validate    ] [bean:lookupValidationService?meth] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.733  INFO 660 --- [           main] o.a.c.Tracing                            :      [validate    ] [direct:db-lookup-${header.lookupT] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.739  INFO 660 --- [           main] o.a.c.Tracing                            : ---> [customer    ] [from[direct:db-lookup-customer]  ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.740  INFO 660 --- [           main] o.a.c.Tracing                            :      [customer    ] [log                              ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.740  INFO 660 --- [           main] o.a.c.Tracing                            :      [customer    ] [setHeader[customerNumber]        ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.891  INFO 660 --- [           main] o.a.c.Tracing                            :      [customer    ] [sql:{{lookup.queries.customer}}?p] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.892  INFO 660 --- [           main] o.a.c.Tracing                            :      [customer    ] [Processor@0x1feb586d             ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupRequest, Body: LookupRequest(keywords={customerNumber=1234678})]
2021-07-12 12:10:13.895  INFO 660 --- [           main] o.a.c.Tracing                            :      [customer    ] [Processor@0x34695b23             ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: null, Body: [{customerName=Test customer}]]
2021-07-12 12:10:13.896  INFO 660 --- [           main] o.a.c.Tracing                            :      [customer    ] [log                              ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupResponse, Body: LookupResponse(ok=true, errorMessage=null, results=[{customerName=Test customer}])]
2021-07-12 12:10:13.896  INFO 660 --- [           main] o.a.c.Tracing                            : <--- [customer    ] [from[direct://db-lookup-customer]] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupResponse, Body: LookupResponse(ok=true, errorMessage=null, results=[{customerName=Test customer}])]
2021-07-12 12:10:13.897  INFO 660 --- [           main] o.a.c.Tracing                            : *<-- [validate    ] [from[direct://validate-request]  ] Exchange[Id: 32F8D8FB9A7CF84-0000000000000000, BodyType: com.odfl.freight.lookupservice.model.LookupResponse, Body: LookupResponse(ok=true, errorMessage=null, results=[{customerName=Test customer}])]
2021-07-12 12:10:13.900  INFO 660 --- [           main] o.a.c.c.m.MockEndpoint                   : Asserting: mock://direct:db-lookup-customer is satisfied

...

java.lang.AssertionError: mock://direct:db-lookup-customer Received message count 0, expected at least 1

    at org.apache.camel.component.mock.MockEndpoint.fail(MockEndpoint.java:1790)
    at org.apache.camel.component.mock.MockEndpoint.assertTrue(MockEndpoint.java:1773)

我是测试 Apache Camel 路由的新手,有人可以帮助我了解问题在哪里或如何验证输出,因为您可以看到交换对象主体在那里并通过。我已经尝试了一些方法来模拟这个endpoint,但似乎没有任何效果,我的想法也没了。

共有1个答案

松桐
2023-03-14

您只使用@MockEndpointsAndSkip(“log:.*”)模拟了logendpoint,并将customerMock注入为mock:direct:dblookupcustomer,但如果它不在路由中,它如何接收消息
我认为您所需要的只是以某种方式模拟您的direct:db查找客户,例如在adviceWith中或使用注释

 类似资料:
  • 我是单元测试新手,我只是想知道如果一个方法在内部调用自己的公共方法来计算返回值,会怎么样,如下所示: 我正在为它编写单元测试,我的问题是:我应该使用特定的整数值来匹配结果和期望值吗

  • 我正在学习使用JUnit。我编写了一个生成严格小于xx的数字的方法。 我想用JUnit测试它。不确定使用哪个断言是基于xX的,我也没有看到任何比较断言。

  • 问题 你想在单元测试中忽略或标记某些测试会按照预期运行失败。 解决方案 unittest 模块有装饰器可用来控制对指定测试方法的处理,例如: import unittest import os import platform class Tests(unittest.TestCase): def test_0(self): self.assertTrue(True)

  • 问题内容: 我正在尝试进行布尔测试,以便如果其中一个胎压低于35或超过45,则系统会输出“不良充气”。 在我的课堂上,我必须使用布尔值,这是我尝试过的。但是,返回的布尔值始终为true。我不明白为什么。 问题答案: 更改为: 甚至更好: 布尔比较运算符为和。该是赋值运算符。 另外,在检查是否违反条件之前,需要进行初始设置。

  • 从Spring 3.1开始,由于@Enable*注释,我们可以更容易地使用JavaConfig。 所以我做了一个WebConfig来设置WebMvc配置,并尝试对其进行测试。但是,如果我使用WebConfig扩展WebMVCConfigureAdapter或WebMvcConfigurationSupport,单元测试将失败,因为缺少ServletContext。代码和消息如下所示。 网络配置。J

  • 任何人谁可以解决这个问题的颤振。请帮帮我。谢谢 失败:生成失败,出现异常。 > 其中:Build file'C:\hello\u everyone\android\app\Build。梯度线:1 错误:评估项目“: app”时出现问题。 在Project类型的project': app'上找不到参数[]org.gradle.api.方法Properties()。 > 尝试:使用--stacktra