2012-08-27 60 views
2

我需要在使用Camel bean組件引用的服務的Grails中編寫生產路徑的單元測試。我的要求是既不改變也不復制現有路線在測試。如何在駱駝生產中模擬Grails服務路徑單元測試

問題是以某種方式模擬服務bean並將其添加到駱駝註冊表。

我能夠在'context.registry.registry'對象上使用'bind'方法來做到這一點。有沒有任何功能可以以更安全的方式來實現?駱駝的版本是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' 
    } 
} 

回答

1

駱駝讓你插件你想要的任何自定義註冊表,開箱即用它採用了基於JNDI註冊表,這就是爲什麼你可以綁定通過代碼示例向其提供服務。另一種方法是使用SimpleRegistry,它只是一個Map,因此您可以使用Map中的put方法將服務放入註冊表中。然後,您需要重寫CamelTestSupport類中的createCamelContext方法,並將SimpleRegistry傳遞給DefaultCamelContext的構造函數。

無論如何,只要您使用非Spring的CamelTestSupport類,您的代碼就很安全,因爲它使用基於JNDI的註冊表。如果你使用CamelSpringTestSupport,那麼它是一個基於Spring的註冊表,你需要使用spring app context來添加你的bean。

+0

謝謝!這回答了我的問題。以上代碼是安全的,直到JNDI註冊表不會在測試類中更改爲其他內容。用SimpleRegistry覆蓋它就能按預期工作。 – droggo

0

您可以使用CamelSpringtestSupport而不是CamelTestSupport來注入組件作爲你的基礎班。

閱讀關於Spring Test的文檔將對您有所幫助,您可能會發現在您的測試中使用模擬很有趣。

無論如何,您可以爲您的測試構建自定義上下文,包含您的bean的聲明並將其加載到測試中。

public class RouteTests extends CamelSpringTestSupport { 

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

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

路由測試context.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> 
+0

我知道,但我不想使用Spring DSL。有一個計劃,以編程的方式構建規則,並使用一些運行時重新加載的東西。答案雖然有幫助,但我還不能投票,謝謝。 – droggo

相關問題