Home > Blockchain >  How to test predicate in an unit test?
How to test predicate in an unit test?

Time:05-26

I have an Apache Camel application, which uses a Choice with a Predicate. How can I test the predicate without an integration test?

Code

@SpringBootApplication
public class TestApplication {

  public static void main(String[] args) {
    SpringApplication.run(TestApplication.class, args);
  }

  @Bean
  public EndpointRouteBuilder route() {
    return new EndpointRouteBuilder() {
      @Override
      public void configure() throws Exception {
        from(file("d:/tmp/camel/"))
            .choice()
            .when(jsonpath("$[?(@.status == 0)]"))
            .log("ok")
            .otherwise()
            .log("not ok");
      }
    };
  }
}

Research

  • I read Test JUnit5, but it looks like an integration test. However, I don't want to test a full route.

  • I read Test Spring JUnit5, but it is an integration test.

Question

How can I extract the predicate jsonpath("$[?(@.status == 0)]") and test it isolated in an unit test with JUnit 5?

CodePudding user response:

Might be hard to accomplish this without a CamelContext. I'd probably approach this with Camel's excellent mocking and stubbing utilities. But if you really just want to isolate the jsonpath expression, you could try something like this:

JsonPathExpression exp = new JsonPathExpression("$[?(@.status == 0)]");
Exchange exchange = new DefaultExchange(context);
final Predicate predicate = exp.createPredicate(context);
exchange.getIn().setBody("{ \"status\": 0 }");
final boolean matches = predicate.matches(exchange);
assertTrue(matches);

Note that you'll still need a CamelContext for this.

Edit: If you just want to test the JsonPath expression outside of Camel:

String jsonPath = "$[?(@.status == 0)]";
String json = "{ \"status\": 0 }";

DocumentContext jsonContext = JsonPath.parse(json);
JSONArray result = jsonContext.read(jsonPath);
assertEquals(1, result.size());

CodePudding user response:

My opinion (you'll probably get 100 more ;-)

Separate that route into another class by itself that can be loaded into the Spring context later.

Use CamelTestSupport to load just Camel (not Spring) in JUnit.

Use Camel "advice" to change "from" to a direct, or create a file (in your test) to exercise the test case you want (once with each branch of the choice.

Again with "advice" change the log to mocks - then after running the file/message you want check to see if the correct mock got a message and the other did not.

  • Related