我正在使用 JUnit 为 Camel 开发单元测试。更具体地说,我正在使用以下库:
org.apache.camel:camel-test-spring-junit5:4.7.0
。当我将 @TestInstance
设置为 TestInstance.LifeCycle.PER_METHOD
时,单元测试工作正常:
@SpringBootTest
@CamelSpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@MockEndpoints("mllp:localhost:2575")
class HelloWorldMllpRouterUnitTest {
@Autowired
private ProducerTemplate template;
@EndpointInject("mock:mllp:localhost:2575")
private MockEndpoint mockEndpoint;
@Test
void whenSendBody_thenHelloWorldReceivedSuccessfully() {
var expectedResponse = "Hello World!";
mockEndpoint.returnReplyBody(ExpressionBuilder.bodyExpression(String.class, func -> expectedResponse));
var resp = template.requestBody("mock:mllp:localhost:2575", "Some request body");
Assertions.assertEquals(expectedResponse, resp);
}
}
但是,当我更改
@TestInstance
使其设置为 TestInstance.LifeCycle.PER_CLASS
(其他条件相同)时,出现以下错误:
在交易所执行时发生异常:Exchange[] org.apache.camel.CamelExecutionException:在交换上执行期间发生异常:Exchange[] 在 org.apache.camel.CamelExecutionException.wrapCamelExecutionException(CamelExecutionException.java:45) 在 org.apache.camel.support.ExchangeHelper.extractResultBody(ExchangeHelper.java:691) 在org.apache.camel.impl.engine.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:591) 在org.apache.camel.impl.engine.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:182) 在org.apache.camel.impl.engine.DefaultProducerTemplate.requestBody(DefaultProducerTemplate.java:372) 在 com.myapp.HelloWorldMllpRouterUnitTest.whenSendBody_thenHelloWorldReceivedSuccessively...
我需要设置
PER_CLASS
标志,因为现有的单元测试使用它。如何让测试与 PER_CLASS
标志集一起工作?
看起来
@CamelSpringBootTest
逻辑有一个标志 "OptionNoStart"
,当该标志为 true 时,会阻止骆驼上下文从 camelContext.start()
开始。似乎有必要在集成测试运行之前打开此标志,以便自定义 Camel 上下文。但是,当设置 PER_CLASS
标志时,"OptionNoStart"
标志似乎会出现错误,并且在实际测试运行时不会关闭。因此,我的解决方案是在所有测试之前简单地将此标志设置为 false
:
@SpringBootTest
@CamelSpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@MockEndpoints("mllp:localhost:2575")
class GreetingsMllpRouterUnitTest {
@Autowired
private ProducerTemplate template;
@EndpointInject("mock:mllp:localhost:2575")
private MockEndpoint mock;
@BeforeAll
public void beforeAll() {
SpringCamelContext.setNoStart(false);
mock.start();
}
@Test
void whenSendBody_thenGreetingReceivedSuccessfully() {
var expectedResponse = "Hello World!";
mock.returnReplyBody(ExpressionBuilder.bodyExpression(String.class, func -> expectedResponse));
var resp = template.requestBody("mock:mllp:localhost:2575", "Hello Baeldung Readers 2!");
Assertions.assertEquals(expectedResponse, resp);
}
}