我在我的应用程序中使用了Apache Camel和Spring Boot。目前,我正在进行单元测试。
Java代码:
DataRoute class
from("direct:getData") .routeId("getData") .bean(DataService.class, "processData") .marshal().json(JsonLibrary.Jackson) .end();
DataService class
public Data processData() { return new Data("Hello World"); }
Data Class with getters, setters and Jackson toString method
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")
在单元测试中,返回一个模拟数据对象,其默认的字符串变量为"Unit test success"。然后测试一下,看看路由是否会返回模拟对象而不是带有"Hello World"字符串变量的对象?