Spina
Spina

Reputation: 9366

How do you unit test a servlet endpoint in apache camel?

I'm new to Camel and now have a simple route running in my Tomcat server. The route is built like this:

Processor generateWebResponse = new MySpecialProcessor();
from("servlet:///url?matchOnUriPrefix=true").process(generateWebResponse);

I tried a simple unit test like this:

Exchange lAuthRequest = createExchangeWithBody("[json body!]");
template.send("servlet:///url", lAuthRequest);
assertEquals("baseline body", lAuthRequest.getOut().getBody());

but get an exception indicating that I can't make a servlet endpoint. Here is the exception message:

org.apache.camel.FailedToCreateProducerException: Failed to create Producer for endpoint: Endpoint[servlet:///url]. Reason: java.lang.UnsupportedOperationException: You cannot create producer with servlet endpoint, please consider to use http or http4 endpoint.

This is new development so I don't have many constraints other than good design. I'm open to suggestions that require changes to the route. Also, if I'm doing something above that isn't idiomatic, I'm happy to revise the question with any suggested improvements.

Upvotes: 5

Views: 4739

Answers (2)

Spina
Spina

Reputation: 9366

I solved my problem by breaking the route into two parts. Now the route declaration looks like this:

from("servlet:///auth?matchOnUriPrefix=true").inOut("direct:auth");
from("direct:auth").process(new AuthorizationProcessor());

And the test looks like this:

Exchange lAuthRequest = createExchangeWithBody("test body");
template.send("direct:auth", lAuthRequest);
assertEquals("processed body", lAuthRequest.getOut().getBody());

This isn't a complete test, but allows me to get coverage of all of the route excluding the incoming servlet part. I think it's sufficient for the time being.

Upvotes: 2

Claus Ibsen
Claus Ibsen

Reputation: 55555

You need to use a http client component to send a message to Tomcat, eg for example the camel--http component: http://camel.apache.org/http

You would then need to know the port number Tomcat runs the servlet at, eg

template.send("http://localhost:8080/myapp/myserver", lAuthRequest);

You would need to add camel-http to your classpath, eg if you use maven then add it as a dependency.

Upvotes: 7

Related Questions