2

我需要为使用 Camel bean 组件引用的服务的 Grails 中的生产路线编写单元测试。我的要求既不是更改也不是复制测试中的现有路线。

问题是以某种方式模拟 Service bean 并将其添加到 Camel 注册表。

我能够使用 'context.registry.registry' 对象上的 'bind' 方法来做到这一点。是否有任何功能可以以更安全的方式做到这一点?Camel 版本是 2.10,Grails 2.1

路线是:

from('direct:validate').to('bean:camelService?method=echo')

CamelService 只是一个简单的类:

package com

class CamelService {
    def echo(text) {
        println "text=$text"
        text
    }
}

测试如下(复制路线只是为了让问题更简单):

package com

import grails.test.mixin.*
import org.apache.camel.builder.RouteBuilder
import org.apache.camel.test.junit4.CamelTestSupport

@TestFor(CamelService)
class RouteTests extends CamelTestSupport {

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from('direct:validate').to('bean:camelService?method=echo')
            }
        };
    }

    void testMockBean() throws Exception {
        context.registry.registry.bind 'camelService', service
        def result = template.requestBody('direct:validate', 'message')
        assert result != null
        assert result == 'message'
    }
}
4

2 回答 2

1

Camel 允许您插入任何您想要的自定义注册表,并且开箱即用它使用基于 Jndi 的注册表,这就是您可以使用代码示例将服务绑定到它的原因。另一种方法是使用 SimpleRegistry,它只是一个 Map,因此您可以使用 Map 中的 put 方法将服务放入注册表。然后,您需要覆盖 CamelTestSupport 类中的 createCamelContext 方法,并将 SimpleRegistry 传递给 DefaultCamelContext 的构造函数。

无论如何,只要您使用非 Spring CamelTestSupport 类,您的代码就是安全的,因为它使用了开箱即用的基于 JNDI 的注册表。如果您使用 CamelSpringTestSupport,那么它是一个基于 spring 的注册表,您需要使用 spring 应用程序上下文将您的 bean 添加到其中。

于 2012-08-28T05:32:46.800 回答
0

您可以使用 CamelSpringtestSupport 而不是 CamelTestSupport 作为基类来注入组件。

阅读有关Spring Test的文档肯定会对您有所帮助,并且您可能会发现在测试中使用 mock 很有趣。

无论如何,您可以为您的测试构建一个自定义上下文,包含您的 bean 声明并将其加载到测试中。

public class RouteTests  extends CamelSpringTestSupport {

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("route-test-context.xml");
    }

    @Test
    public void testMockBean(){
         //...
    }
}

路由测试上下文.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cxf="http://camel.apache.org/schema/cxf" xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://camel.apache.org/schema/spring 
     http://camel.apache.org/schema/spring/camel-spring.xsd">

     <bean id="service" ref="com.CamelService"/>
     <camelContext xmlns="http://camel.apache.org/schema/spring">
          <package>com</package>
     </camelContext>
</beans>
于 2012-08-27T14:34:44.357 回答