gpt4 book ai didi

unit-testing - Apache Camel bean 单元测试

转载 作者:行者123 更新时间:2023-12-05 06:41:26 28 4
gpt4 key购买 nike

我在我的应用程序中使用 Apache Camel 和 Spring boot。目前我正在进行单元测试。

Java代码

  • 数据路由类

    from("direct:getData")
    .routeId("getData")
    .bean(DataService.class, "processData")
    .marshal().json(JsonLibrary.Jackson)
    .end();
  • 数据服务类

    public Data processData() {
    return new Data("Hello World");
    }
  • 具有 getter、setter 和 Jackson toString 方法的数据类

    private String value;

单元测试

  • BaseCamelContextUnitText

    public abstract class BaseCamelContextUnitTest extends CamelTestSupport
    {
    @Autowired
    private DataService dataService;

    @Produce
    private ProducerTemplate producerTemplate;

    public CamelContext getCamelContext() {
    return camelContext;
    }

    @Override
    protected Context createJndiContext() throws Exception {
    JndiContext context = new JndiContext();
    context.bind("dataService", dataService);
    return context;
    }

    @Test
    public void shouldProcessData() throws Exception {
    RouteDefinition routeDef = getCamelContext().getRouteDefinition("getData");
    routeDef.adviceWith((ModelCamelContext) getCamelContext(), new RouteBuilder() {

    @Override
    public void configure() throws Exception {
    from("direct:getData")
    .pipeline("bean:dataService?method=processData");
    }
    });

    getCamelContext().start();

    String responseData = "{"
    + "\"value\":\"Unit test success\""
    + "}";

    Object response = producerTemplate.sendBody("direct:getData", ExchangePattern.InOut, null);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ((InputStreamCache) response).writeTo(byteArrayOutputStream);

    assertThat(new String(byteArrayOutputStream.toByteArray()), is(responseData));
    }
    }

我如何模拟

   .bean(DataService.class, "processData")

在单元测试中返回一个带有默认字符串变量的模拟数据对象,比如“单元测试成功”,然后测试路由是否会返回模拟对象而不是带有“Hello World”字符串变量的对象?

最佳答案

这似乎是一个迟到的回应,但我遇到了与您的案例中描述的相同的事情,并且我遇到了一种“模拟”bean 步骤的简单方法,即使用 DefaultRegistry 进行注册将模拟的 bean 放入 Camel 注册表中,例如:

@Test
public void shouldProcessData() throws Exception {
...
...
DataService dataService = new DataService(...);
stubBean("dataService", dataService); // put this before calling context.start();

context.start();
...
...
}


/**
* This method inject a stub bean into the registry
* @param beanName the name of the bean being injected
* @param instance the stub instance
*/
void stubBean(String beanName, Object instance) {
DefaultRegistry registry = context.getRegistry(DefaultRegistry.class);
registry.bind(beanName, instance);
}

关于unit-testing - Apache Camel bean 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40538987/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com