Camel testing: bean, ref or beanType must be provided
I recently got this error in Camel during unit testing:
Caused by: java.lang.IllegalArgumentException: bean, ref or beanType must be provided
In case others come across the same issue, I thought I’d do a quick write-up on what the solution in my specific scenario was. Consider these production code extracts:
// File: InputDataValidator.java
@Component
public class InputDataValidator {
public Processor validate() {
return exchange -> {
// Validate data
exchange.getIn();
};
}
public Processor validateSomethingElse() {
return exchange -> {
// Validate data
exchange.getIn();
};
}
}
// File: MyRoute.java
@Component
public class MyRoute extends RouteBuilder {
private InputDataValidator inputDataValidator;
@Autowired
public MyRoute(InputDataValidator inputDataValidator) {
this.inputDataValidator = inputDataValidator;
}
@Override
public void configure() {
from("direct:input")
.bean(this.inputDataValidator.validate()); // This did not work
}
}
The unit test:
// File: MyRouteTest.java
@CamelSpringBootTest
@SpringBootTest(classes = {MyApplication.class})
@UseAdviceWith
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class MyRouteTest {
@MockBean
private InputDataValidator mockedValidator;
@Autowired
private CamelContext context;
@Test
public void test() throws Exception {
String errorMessage = "ERROR";
doThrow(new ValidationException(errorMessage)).when(mockedValidator).validate();
context.start();
FluentProducerTemplate fluentProducerTemplate;
fluentProducerTemplate = context.createFluentProducerTemplate().to(ROUTE_DIRECT_VALIDERE_OPPSLAG);
Message result = fluentProducerTemplate.withHeader("key", "value").request(Message.class);
assertEquals(400, result.getHeader("CamelHttpResponseCode"));
assertEquals(Feil.class, result.getBody().getClass());
assertEquals("400", (result.getBody(Feil.class).getKode()));
assertEquals(errorMessage, (result.getBody(Feil.class).getMelding()));
}
}
When running the unit test, I got the error referenced in the title:
java.lang.IllegalArgumentException: bean, ref or beanType must be provided
To get the test to work, just a very small adjustment to the production code was required:
from("direct:input")
// .bean(this.inputDataValidator.validate()); // This did not work
.bean(this.inputDataValidator, "validate"); // This worked
I’m running Camel 3.18.1.