junit - Apache Camel Beans Unit Testing -
i using apache camel spring boot in application. working on unit test.
java code
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 getters, setters , jackson tostring method
private string value;
unit test
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)); } }
how mock
.bean(dataservice.class, "processdata") in unit test return mock data object default string variable "unit test success" , test see if route give mocked object instead of object "hello world" string variable?
you can autowired dataservice in dataroute like
@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(); } } so can mock dataservice usual.
an alternative using beanref("beanname", "methodname") in route.
Comments
Post a Comment