Java Code Examples for org.apache.camel.component.mock.MockEndpoint#expectedMessageCount()

The following examples show how to use org.apache.camel.component.mock.MockEndpoint#expectedMessageCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpringSplitterStopOnExceptionABCTest.java    From camelinaction2 with Apache License 2.0 7 votes vote down vote up
@Test
public void testSplitStopOnException() throws Exception {
    MockEndpoint split = getMockEndpoint("mock:split");
    // we expect 1 messages to be split since the 2nd message should fail
    split.expectedBodiesReceived("Camel rocks");

    // and no combined aggregated message since we stop on exception
    MockEndpoint result = getMockEndpoint("mock:result");
    result.expectedMessageCount(0);

    // now send a message with an unknown letter (F) which forces an exception to occur
    try {
        template.sendBody("direct:start", "A,F,C");
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        CamelExchangeException cause = assertIsInstanceOf(CamelExchangeException.class, e.getCause());
        IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, cause.getCause());
        assertEquals("Key not a known word F", iae.getMessage());
    }

    assertMockEndpointsSatisfied();
}
 
Example 2
Source File: JingIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testJingRngSchemaValidationFailure() throws Exception {
    CamelContext camelctx = createCamelContext(false);

    MockEndpoint mockEndpointValid = camelctx.getEndpoint("mock:valid", MockEndpoint.class);
    mockEndpointValid.expectedMessageCount(0);

    MockEndpoint mockEndpointInvalid = camelctx.getEndpoint("mock:invalid", MockEndpoint.class);
    mockEndpointInvalid.expectedMessageCount(1);

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:start", ORDER_XML_INVALID);

        mockEndpointValid.assertIsSatisfied();
        mockEndpointInvalid.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 3
Source File: FirstMockTest.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
@Test
public void testContains() throws Exception {
    // get the mock endpoint
    MockEndpoint quote = getMockEndpoint("mock:quote");
    // set expectations the two messages arrives in specified order
    quote.expectedMessageCount(2);
    // all messages should contain the Camel word
    quote.allMessages().body().contains("Camel");

    // fire in a messages to Camel
    template.sendBody("jms:topic:quote", "Hello Camel");
    template.sendBody("jms:topic:quote", "Camel rocks");

    // verify the result
    quote.assertIsSatisfied();
}
 
Example 4
Source File: SplitReaggregateTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testSplitAggregatesResponsesCombined() throws Exception {
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.expectedMessageCount(2);

    String filename = "target/classes/xml/books-extended.xml";
    assertFileExists(filename);
    InputStream booksStream = new FileInputStream(filename);

    template.sendBody("direct:combined", booksStream);

    assertMockEndpointsSatisfied();
    List<Exchange> receivedExchanges = mockOut.getReceivedExchanges();
    assertBooksByCategory(receivedExchanges.get(0));
    assertBooksByCategory(receivedExchanges.get(1));
}
 
Example 5
Source File: DlcTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testDlqUseOriginal() throws Exception {
    final MockEndpoint mockResult = getMockEndpoint("mock:result");
    mockResult.expectedMessageCount(1);
    mockResult.expectedBodiesReceived("Foo");
    mockResult.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isNull();
    mockResult.message(0).header("myHeader").isEqualTo("changed");

    final MockEndpoint mockError = getMockEndpoint("mock:error");
    mockError.expectedMessageCount(1);
    mockError.expectedBodiesReceived("KaBoom");
    mockError.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isNotNull();
    mockError.message(0).exchangeProperty(Exchange.FAILURE_ROUTE_ID).isEqualTo("myDlcOriginalRoute");
    mockError.message(0).header("myHeader").isEqualTo("original");

    template.sendBodyAndHeader("direct:useOriginal", "Foo", "myHeader", "original");
    template.sendBodyAndHeader("direct:useOriginal", "KaBoom", "myHeader", "original");

    assertMockEndpointsSatisfied();
}
 
Example 6
Source File: StaxIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testStaxJAXBSplit() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .split(stax(Record.class)).streaming()
            .to("mock:result");
        }
    });

    MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
    mockEndpoint.expectedMessageCount(5);
    mockEndpoint.allMessages().body().isInstanceOf(Record.class);

    camelctx.start();
    try (InputStream input = getClass().getResourceAsStream("/" + RECORDS_XML)) {
        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:start", input);
        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 7
Source File: SpringSecondMockTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsCamelMessage() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:quote");
    mock.expectedMessageCount(2);

    template.sendBody("stub:jms:topic:quote", "Hello Camel");
    template.sendBody("stub:jms:topic:quote", "Camel rocks");

    assertMockEndpointsSatisfied();

    List<Exchange> list = mock.getReceivedExchanges();
    String body1 = list.get(0).getIn().getBody(String.class);
    String body2 = list.get(1).getIn().getBody(String.class);
    assertTrue(body1.contains("Camel"));
    assertTrue(body2.contains("Camel"));
}
 
Example 8
Source File: PurchaseOrderCsvTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
   public void testCsv() throws Exception {
       MockEndpoint mock = getMockEndpoint("mock:queue.csv");
       mock.expectedMessageCount(2);

       assertMockEndpointsSatisfied();

       List line1 = mock.getReceivedExchanges().get(0).getIn().getBody(List.class);
       assertEquals("Camel in Action", line1.get(0));
       assertEquals("6999", line1.get(1));
       assertEquals("1", line1.get(2));

       List line2 = mock.getReceivedExchanges().get(1).getIn().getBody(List.class);
       assertEquals("Activemq in Action", line2.get(0));
       assertEquals("4495", line2.get(1));
       assertEquals("2", line2.get(2));
   }
 
Example 9
Source File: DataVecComponentTest.java    From DataVec with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataVec() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    //1
    mock.expectedMessageCount(1);

    RecordReader reader = new CSVRecordReader();
    reader.initialize(new FileSplit(new ClassPathResource("iris.dat").getFile()));
    Collection<Collection<Writable>> recordAssertion = new ArrayList<>();
    while (reader.hasNext())
        recordAssertion.add(reader.next());
    mock.expectedBodiesReceived(recordAssertion);
    assertMockEndpointsSatisfied();
}
 
Example 10
Source File: RetryTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryRouteSpecific() throws Exception {
    final MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
    mockEndpoint.expectedMessageCount(1);
    mockEndpoint.allMessages().header(Exchange.REDELIVERED).isEqualTo(true);
    mockEndpoint.allMessages().header(Exchange.REDELIVERY_COUNTER).isEqualTo(1);
    mockEndpoint.allMessages().header(Exchange.REDELIVERY_MAX_COUNTER).isEqualTo(2);
    mockEndpoint.allMessages().header(Exchange.REDELIVERY_DELAY).isNull();

    template.sendBody("direct:routeSpecific", "Foo");

    assertMockEndpointsSatisfied();
}
 
Example 11
Source File: QuteLetterTest.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testQute() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    mock.message(0).body(String.class).contains("Thanks for the order of Camel in Action");

    template.send("direct:a", createLetter());

    mock.assertIsSatisfied();
}
 
Example 12
Source File: SplitXmlNamespacesTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitArray() throws Exception {
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.expectedMessageCount(2);
    mockOut.expectedBodiesReceived("Scott Cranton", "Jakub Korab");

    String filename = "target/classes/xml/books-ns.xml";
    assertFileExists(filename);
    InputStream booksStream = new FileInputStream(filename);

    template.sendBody("direct:in", booksStream);

    assertMockEndpointsSatisfied();
}
 
Example 13
Source File: ComponentProxySplitCollectionTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplit() throws InterruptedException {
    final ProducerTemplate template = camelContext.createProducerTemplate();
    final MockEndpoint mock = camelContext.getEndpoint("mock:result", MockEndpoint.class);
    final String[] values = { "a","b","c" };

    mock.expectedMessageCount(values.length);
    mock.expectedBodiesReceived((Object[])values);

    template.sendBody("direct:start", Arrays.asList(values));

    mock.assertIsSatisfied();
}
 
Example 14
Source File: SplitAggregateTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitAggregatesResponses() throws Exception {
    String[] array = new String[]{"one", "two", "three"};

    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.expectedMessageCount(1);

    template.sendBody("direct:in", array);

    assertMockEndpointsSatisfied();
    Exchange exchange = mockOut.getReceivedExchanges().get(0);
    @SuppressWarnings("unchecked")
    Set<String> backendResponses = Collections.checkedSet(exchange.getIn().getBody(Set.class), String.class);
    assertTrue(backendResponses.containsAll(Arrays.asList("Processed: one", "Processed: two", "Processed: three")));
}
 
Example 15
Source File: SplitterBeanTest.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitBean() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:split");
    mock.expectedMessageCount(3);

    Customer customer = CustomerService.createCustomer();

    template.sendBody("direct:start", customer);

    assertMockEndpointsSatisfied();
}
 
Example 16
Source File: ManageTracerMain.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
public void testManageTracer() throws Exception {
    System.out.println("Connect to JConsole and try managing Tracer by enabling and disabling it on individual routes");

    MockEndpoint mock = context.getEndpoint("jms:queue:orders", MockEndpoint.class);
    mock.expectedMessageCount(100);

    for (int i = 0; i < 100; i++) {
        template.sendBody("file://target/rider/orders", "" + i + ",4444,20100110,222,1");
    }

    mock.await(100 * 10, TimeUnit.SECONDS);

    System.out.println("Complete sending 100 files will stop now");
}
 
Example 17
Source File: KnativeSourceRoutesLoaderTest.java    From camel-k-runtime with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("parameters")
public void testWrapLoader(String uri) throws Exception {
    LOGGER.info("uri: {}", uri);

    final String data = UUID.randomUUID().toString();
    final TestRuntime runtime = new TestRuntime();

    KnativeComponent component = new KnativeComponent();
    component.setEnvironment(KnativeEnvironment.on(
        KnativeEnvironment.endpoint(Knative.EndpointKind.sink, "sink", "localhost", runtime.port)
    ));

    CamelContext context = runtime.getCamelContext();
    context.addComponent(KnativeConstants.SCHEME, component);

    Source source = Sources.fromURI(uri);
    SourceLoader loader = RoutesConfigurer.load(runtime, source);

    assertThat(loader.getSupportedLanguages()).contains(source.getLanguage());
    assertThat(runtime.builders).hasSize(1);

    try {
        context.addRoutes(runtime.builders.get(0));
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                fromF("platform-http:/")
                    .routeId("http")
                    .to("mock:result");
            }
        });
        context.start();

        List<RouteDefinition> definitions = context.adapt(ModelCamelContext.class).getRouteDefinitions();

        assertThat(definitions).hasSize(2);
        assertThat(definitions).first().satisfies(d -> {
            assertThat(d.getOutputs()).last().hasFieldOrPropertyWithValue(
                "endpointUri",
                "knative://endpoint/sink"
            );
        });

        MockEndpoint mock = context.getEndpoint("mock:result", MockEndpoint.class);
        mock.expectedMessageCount(1);
        mock.expectedBodiesReceived(data);

        context.createFluentProducerTemplate()
            .to("direct:start")
            .withHeader("MyHeader", data)
            .send();

        mock.assertIsSatisfied();
    } finally {
        context.stop();
    }
}
 
Example 18
Source File: UndertowWsIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void fireWebSocketChannelEvents() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            final int port = getPort();
            /* sendToAll */
            from("undertow:ws://localhost:" + port + "/app5?fireWebSocketChannelEvents=true") //
                    .to("mock:result5") //
                    .to("undertow:ws://localhost:" + port + "/app5");
        }

    });

    camelctx.start();
    try {

        MockEndpoint result = camelctx.getEndpoint("mock:result5", MockEndpoint.class);
        result.expectedMessageCount(6);

        TestClient wsclient1 = new TestClient("ws://localhost:" + getPort() + "/app5", 2);
        TestClient wsclient2 = new TestClient("ws://localhost:" + getPort() + "/app5", 2);
        wsclient1.connect();
        wsclient2.connect();

        wsclient1.sendTextMessage("Gambas");
        wsclient2.sendTextMessage("Calamares");

        wsclient1.close();
        wsclient2.close();

        result.await(60, TimeUnit.SECONDS);

        final List<Exchange> exchanges = result.getReceivedExchanges();
        final Map<String, List<String>> connections = new HashMap<>();
        for (Exchange exchange : exchanges) {
            final Message in = exchange.getIn();
            final String key = (String) in.getHeader(UndertowConstants.CONNECTION_KEY);
            Assert.assertNotNull(key);
            List<String> messages = connections.get(key);
            if (messages == null) {
                messages = new ArrayList<String>();
                connections.put(key, messages);
            }
            String body = in.getBody(String.class);
            if (body != null) {
                messages.add(body);
            } else {
                messages.add(in.getHeader(UndertowConstants.EVENT_TYPE_ENUM, EventType.class).name());
            }
        }

        final List<String> expected1 = Arrays.asList(EventType.ONOPEN.name(), "Gambas", EventType.ONCLOSE.name());
        final List<String> expected2 = Arrays.asList(EventType.ONOPEN.name(), "Calamares",
                EventType.ONCLOSE.name());

        Assert.assertEquals(2, connections.size());
        final Iterator<List<String>> it = connections.values().iterator();
        final List<String> actual1 = it.next();
        Assert.assertTrue("actual " + actual1, actual1.equals(expected1) || actual1.equals(expected2));
        final List<String> actual2 = it.next();
        Assert.assertTrue("actual " + actual2, actual2.equals(expected1) || actual2.equals(expected2));
    } finally {
        camelctx.close();
    }

}
 
Example 19
Source File: KnativeHttpTest.java    From camel-k-runtime with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@EnumSource(CloudEvents.class)
void testConsumeContent(CloudEvent ce) throws Exception {
    configureKnativeComponent(
        context,
        ce,
        sourceEndpoint(
            "myEndpoint",
            mapOf(
                Knative.KNATIVE_EVENT_TYPE, "org.apache.camel.event",
                Knative.CONTENT_TYPE, "text/plain"
            ))
    );

    RouteBuilder.addRoutes(context, b -> {
        b.from("knative:endpoint/myEndpoint")
            .to("mock:ce");
    });

    context.start();

    MockEndpoint mock = context.getEndpoint("mock:ce", MockEndpoint.class);
    mock.expectedHeaderReceived(CloudEvent.CAMEL_CLOUD_EVENT_VERSION, ce.version());
    mock.expectedHeaderReceived(CloudEvent.CAMEL_CLOUD_EVENT_TYPE, "org.apache.camel.event");
    mock.expectedHeaderReceived(CloudEvent.CAMEL_CLOUD_EVENT_ID, "myEventID");
    mock.expectedHeaderReceived(CloudEvent.CAMEL_CLOUD_EVENT_SOURCE, "/somewhere");
    mock.expectedHeaderReceived(Exchange.CONTENT_TYPE, "text/plain");
    mock.expectedMessagesMatches(e -> e.getMessage().getHeaders().containsKey(CloudEvent.CAMEL_CLOUD_EVENT_TIME));
    mock.expectedBodiesReceived("test");
    mock.expectedMessageCount(1);

    given()
        .body("test")
        .header(Exchange.CONTENT_TYPE, "text/plain")
        .header(ce.mandatoryAttribute(CloudEvent.CAMEL_CLOUD_EVENT_VERSION).http(), ce.version())
        .header(ce.mandatoryAttribute(CloudEvent.CAMEL_CLOUD_EVENT_TYPE).http(), "org.apache.camel.event")
        .header(ce.mandatoryAttribute(CloudEvent.CAMEL_CLOUD_EVENT_ID).http(), "myEventID")
        .header(ce.mandatoryAttribute(CloudEvent.CAMEL_CLOUD_EVENT_TIME).http(), DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()))
        .header(ce.mandatoryAttribute(CloudEvent.CAMEL_CLOUD_EVENT_SOURCE).http(), "/somewhere")
    .when()
        .post()
    .then()
        .statusCode(200);

    mock.assertIsSatisfied();
}
 
Example 20
Source File: SplitStepHandlerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSplitJsonArrayInpuStream() throws Exception {
    final DefaultCamelContext context = new DefaultCamelContext();

    try {
        final RouteBuilder routes = newIntegrationRouteBuilder(activityTracker,
                new Step.Builder()
                    .id(START_STEP)
                    .stepKind(StepKind.endpoint)
                    .action(new ConnectorAction.Builder()
                        .descriptor(new ConnectorDescriptor.Builder()
                            .componentScheme("direct")
                            .putConfiguredProperty("name", "expression")
                            .build())
                        .build())
                    .build(),
                new Step.Builder()
                    .id(SPLIT_STEP)
                    .stepKind(StepKind.split)
                    .build(),
                new Step.Builder()
                    .id(MOCK_STEP)
                    .stepKind(StepKind.endpoint)
                    .action(new ConnectorAction.Builder()
                        .descriptor(new ConnectorDescriptor.Builder()
                            .componentScheme("mock")
                            .putConfiguredProperty("name", "expression")
                            .build())
                        .build())
                    .build()
        );

        // Set up the camel context
        context.setUuidGenerator(KeyGenerator::createKey);
        context.addLogListener(new IntegrationLoggingListener(activityTracker));
        context.addInterceptStrategy(new ActivityTrackingInterceptStrategy(activityTracker));
        context.addRoutes(routes);

        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        final ProducerTemplate template = context.createProducerTemplate();
        final MockEndpoint result = context.getEndpoint("mock:expression", MockEndpoint.class);
        final String body = "[{\"id\": 1, \"name\": \"a\"},{\"id\": 2, \"name\": \"b\"},{\"id\": 3, \"name\": \"c\"}]";

        result.expectedMessageCount(3);
        result.expectedBodiesReceived("{\"id\":1,\"name\":\"a\"}", "{\"id\":2,\"name\":\"b\"}", "{\"id\":3,\"name\":\"c\"}");

        template.sendBody("direct:expression", new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));

        result.assertIsSatisfied();

        verify(activityTracker).startTracking(any(Exchange.class));
        verifyActivityStepTracking(SPLIT_STEP, 0);
        verifyActivityStepTracking(MOCK_STEP, 3);
        verify(activityTracker).finishTracking(any(Exchange.class));
    } finally {
        context.stop();
    }
}