2016-11-10 208 views
1

我在我的應用程序中使用Apache Camel和Spring引導。目前我正在進行單元測試。阿帕奇駱駝豆單元測試

Java代碼的

  • DataRoute類

    from("direct:getData") 
    .routeId("getData") 
    .bean(DataService.class, "processData") 
    .marshal().json(JsonLibrary.Jackson) 
    .end(); 
    
  • DataService類

    public Data processData() { 
        return new Data("Hello World"); 
    } 
    
  • 數據類的getter,setter和傑克遜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」字符串變量的對象?

回答

0

您可以在DataRoute自動裝配的DataService

@Component 
public class DataRoute extends RouteBuilder { 

    @Autowired 
    private DataService dataService; 

    @Override 
    public void configure() throws Exception { 
     from("direct:getData") 
     .routeId("getData") 
     .bean(dataService, "processData") 
     .marshal().json(JsonLibrary.Jackson) 
     .end(); 
    } 

} 

所以,你可以嘲笑DataService如常。

另一種方法是在路線中使用beanRef("beanName", "methodName")