I need to write JUNIT for Apache camel route - junit

I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this

You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}

Related

Getting NullPointerException while accessing the SuperClass method call using powermock

Getting NullPointerException while accessing the SuperClass method call using powermock
While running the below mentioned testclass getting NullPointerException error at above mentioned line in switch(super.getType())
public class CommandParamInput extends AbstractCommandParam {
public CommandParamInput(
final ParameterFeedType commandParameterSourceToSet,
final Object definedValueToSet) {
this.commandParameterSource = commandParameterSourceToSet;
this.definedValue = definedValueToSet;
}
public void evaluateValue(final FDPRequest fdpRequest)
throws EvaluationFailedException {
switch (super.getType()) {
case ARRAY:
evaluateComplexValue(fdpRequest);
break;
}
}
}
While running the below mentioned testclass getting NullPointerException error at above mentioned line in switch(super.getType())
#RunWith(PowerMockRunner.class)
#PrepareForTest({AbstractCommandParam.class,CommandParameterType.class,ParameterFeedType.class,LoggerUtil.class,Logger.class})
public class CommandParamInputTest {
private Logger loggerMock;
private FDPRequest instFDPRequest;
private FDPResponse instFDPResponse;
private FDPCacheable instFDPCacheable;
private AbstractCommandParam cmdParam;
private CommandParamInput spy;
#Mock
AbstractCommandParam absCommandParam;
#Mock
CommandParameterType cmdParameterType;
#Mock
ParameterFeedType parameterFeedType;
#InjectMocks
private CommandParamInput commandParamInput;
#Before
public void init() {
FDPRequestImpl fdoRequestImpl = new FDPRequestImpl();
fdoRequestImpl.setCircle(new FDPCircle(new Long(10),"10","test"));
fdoRequestImpl.setChannel(ChannelType.USSD);
instFDPRequest = fdoRequestImpl;
spy = PowerMockito.spy(new CommandParamInput(parameterFeedType.AUX_REQUEST_PARAM, instFDPCacheable));
}
#Test
public void testEvaluateValue()throws ExecutionFailedException,
EvaluationFailedException, FileNotFoundException, RuleException{
mockCommonObjects();
commonMockExternalCall();
absCommandParam = new CommandParamInput(parameterFeedType.AUX_REQUEST_PARAM, instFDPCacheable);
absCommandParam.setType(cmdParameterType.PARAM_IDENTIFIER);
PowerMockito.doReturn(cmdParameterType.PARAM_IDENTIFIER).when(spy).getType();
// when(absCommandParam.getType()).thenReturn(cmdParameterType.PARAM_IDENTIFIER);
PowerMockito.suppress(PowerMockito.methods(AbstractCommandParam.class, "getType"));
commandParamInput.evaluateValue(instFDPRequest);
}
}

Mocking an injected object in a method return and UnsupportedOperationException method

I have a class that returns an injected object using Mockito. Everytime I test it, it returns a bull. How would I properly test it to return the correct object?
My class to test:
#Component
public class CarImpl {
#Inject
private Engine v6EngineImpl;
public Engine getEngine() {
return v6EngineImpl;
}
public Exhaust getExhaust() {
throw new UnsupportedOperationException("unsupported");
}
}
Tests:
#RunWith(MockitoJUnitRunner.class)
public class CarTest {
#InjectMocks
private CarImpl carImpl;
#Mock
private Engine v6EngineImpl;
#Test
public void testGetEngine(){
Engine v6EngineImpl = mock(V6EngineImpl.class);
Engine engine = carImpl.getEngine();
// always returns a bull no matter what, how to mock inject.
//return object correctly?
Assert.assertNotNull(engine);
}
#Test
public void testGetExhaust() {
// how to test thrown exception?
}
}
Thanks, I am not too familiar thanks
Try this:
#RunWith(MockitoJUnitRunner.class)
public class CarTest {
#InjectMocks
private CarImpl carImpl;
#Mock
private Engine v6EngineImpl;
#Test
public void testGetEngine(){
Engine engine = carImpl.getEngine();
//engine is the mock injected to CarImpl
Assert.assertNotNull(engine);
Assert.assertSame(engine,v6EngineImpl);
}
#Test(expected=UnsupportedOperationException.class)
public void testGetExhaust() {
carImpl.getExhaust();
}
}

Test play controller with session data

I have a simple controller test.
route(fakeRequest(routes.Accounts.accounts()).session("sessionref","fakeSession"));
Secured Autheticator looks like this:
public class Secured extends play.mvc.Security.Authenticator {
#Inject
AuthServices authService;
public String getUsername(Http.Context context) {
return authService.checkSession(context);
}
#Override
public Result onUnauthorized(Http.Context context) {
return ok(index.render(formFactory.form(forms.LoginForm.class)));
}
}
How can i mock authService?
I tried to mock with guice bind but this method don't work
#Before
public void setup() {
startPlay();
MockitoAnnotations.initMocks(this);
Module testModule = new AbstractModule() {
#Override
public void configure() {
bind(AuthServices.class)
.toInstance(authServices);
}
};
GuiceApplicationBuilder builder = new GuiceApplicationLoader()
.builder(new play.ApplicationLoader.Context(Environment.simple()))
.in(Mode.TEST)
.overrides(testModule);
Guice.createInjector(builder.applicationModule()).injectMembers(this);
}
You can read this for testing Play controllers and follow this example for testing with Guice.
For your case it is something like this:
public class MyTest extends WithApplication {
#Mock
AuthServices mockAuthService;
#Override
protected Application provideApplication() {
return new GuiceApplicationBuilder()
.overrides(bind(CacheProvider.class).toInstance(mockAuthService))
.in(Mode.TEST)
.build();
}
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testAccounts() {
running(provideApplication(), () -> {
RequestBuilder testRequest = Helpers.fakeRequest(controllers.routes.Accounts.accounts()).session("sessionref","fakeSession");
Result result = route(testRequest);
//assert here the expected result
});
}
}

Configure 2 different MessageConverters for 2 Controllers

I would like to configure two different HttpMessageConverters having the same MediaType for two separate controllers. The reason is that there are some external services that uses different JSON formats. We are not able to change them.
Is it possible? Can I create two WebMvcConfigurerAdapters and split the traffic somehow? If possible, is it a good practice?
Finally, I solved the problem by overriding MessageConverter adding possiblity to configure its jaxbcontext and assign supported packages. So, then I can create 2 different MesssageConverters for the same controller and depending on a return class use one or another.
public class MoxyMessageConverter extends AbstractHttpMessageConverter<Object> {
private final JAXBContext jAXBContext;
private String[] supportedPackages = { ... }; // some defaults
public MoxyMessageConverter(JAXBContext jAXBContext) {
this.jAXBContext = jAXBContext;
}
public String[] getSupportedPackages() {
return supportedPackages;
}
public void setSupportedPackages(String[] supportedPackages) {
this.supportedPackages = supportedPackages;
}
#Override
protected boolean supports(Class<?> clazz) {
String packageName = clazz.getPackage().getName();
for (String supportedPackage : supportedPackages) {
if (packageName.startsWith(supportedPackage))
return true;
}
return false;
}
#Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
..
}
#Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
..
}
}
and in the #Configuration class:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
super.extendMessageConverters(converters);
MoxyMessageConverter defaultMessageConverter = new MoxyMessageConverter(defaultJAXBContext);
defaultMessageConverter.setSupportedPackages(new String[] { "xxx.xxx.xxx.webservices" });
converters.add(0, defaultMessageConverter );
MoxyMessageConverter payUMessageConverter = new MoxyMessageConverter(payUJAXBContext);
payUMessageConverter.setSupportedPackages(new String[] { "xxx.xxx.xxx.webservices.payu" });
converters.add(0, payUMessageConverter);
}
}

Junits for classes extending QuartzJobBean

I have a Java class that extends QuartzJobBean and has been scheduled at a specific time through out the day.
public class ServiceJob extends QuartzJobBean {
#Override
protected void executeInternal(JobExecutionContext context) {
}
Can someone please help me understand how to create a Junit test case for this. How do I invoke the executeInternal() method in the test case.
Thanks for any help on this.
I create a solution for my working project, i agree to adarshdatt to solve it via importing config file that defined the bean. You can find a good tutorial about it at this blog post,
For future use I want to show how i solve it with Mocking, just use Mockito #Mock annotation with this way :
SessionConfirmationJob.java
public class SessionConfirmationJob extends QuartzJobBean {
#Autowired
private SessionService sessionService;
#Autowired
private TransactionService transactionService;
#Autowired
private SystemLogger systemLogger;
public static final String TOKEN = "token";
private SpringInjectQuartzJobBean springInjectQuartzJobBean;
public SessionService getSessionService() {
return sessionService;
}
public void setSessionService(SessionService sessionService) {
this.sessionService = sessionService;
}
public TransactionService getTransactionService() {
return transactionService;
}
public void setTransactionService(TransactionService transactionService) {
this.transactionService = transactionService;
}
public void setSpringInjectQuartzJobBean(SpringInjectQuartzJobBean springInjectQuartzJobBean) {
this.springInjectQuartzJobBean = springInjectQuartzJobBean;
}
public SystemLogger getSystemLogger() {
return systemLogger;
}
public void setSystemLogger(SystemLogger systemLogger) {
this.systemLogger = systemLogger;
}
#Override
protected void executeInternal(JobExecutionContext paramJobExecutionContext) throws JobExecutionException {
springInjectQuartzJobBean = new SpringInjectQuartzJobBean();
springInjectQuartzJobBean.injectQuartzJobToSpringApplicationContext(this);
String token = paramJobExecutionContext.getMergedJobDataMap().getString(TOKEN);
Session session = sessionService.getByToken(token);
if (session != null) {
if (session.getPaymentConfirmation() == null || session.getPaymentConfirmation() != true) {
Transaction transactionToBeRolledBack = transactionService.getRollBackTransactionOfPayment(session);
if (transactionToBeRolledBack != null) {
try {
transactionService.rollBackTransaction(transactionToBeRolledBack);
} catch (IOException e) {
systemLogger.logException("Exception while rolling back transaction", e);
}
session = sessionService.getByToken(token);
session.setStatus(SessionStatus.FI);
session.setPaymentConfirmation(false);
sessionService.saveOrUpdate(session);
}
}
}
}
}
This is the method i should write test and this is the testing class.
SessionConfirmationJobTest.java
#RunWith(MockitoJUnitRunner.class)
public class SessionConfirmationJobTest {
#Mock
private SessionService sessionService;
#Mock
private TransactionService transactionService;
#Mock
private JobExecutionContext ctx;
#Mock
private SpringInjectQuartzJobBean springInjectQuartzJobBean;
private JobDataMap mergedJobDataMap = new JobDataMap();
#Mock
private Scheduler scheduler;
private SessionConfirmationJob sessionConfirmationJob;
private String token = "payment token";
#Before
public void setUp() throws SchedulerException {
mergedJobDataMap.put(SessionConfirmationJob.TOKEN, token);
when(ctx.getMergedJobDataMap()).thenReturn(mergedJobDataMap);
when(ctx.getScheduler()).thenReturn(scheduler);
when(scheduler.getContext()).thenReturn(null);
sessionConfirmationJob = new SessionConfirmationJob();
sessionConfirmationJob.setSessionService(sessionService);
sessionConfirmationJob.setTransactionService(transactionService);
sessionConfirmationJob.setSpringInjectQuartzJobBean(springInjectQuartzJobBean);
}
/**
* Test payment confirmation when we have false payment confirmation
*
* #throws JobExecutionException
*/
#Test
public void testPaymentRollBackForFalseConfirmation() throws IOException, JobExecutionException {
Session session = new Session();
session.setStatus(SessionStatus.AC);
session.setPaymentConfirmation(false);
Transaction transaction = new Transaction();
transaction.setSession(session);
transaction.setType(TransactionType.SALE);
transaction.setStatus(TransactionStatus.AP);
when(sessionService.getByToken(token)).thenReturn(session);
when(transactionService.getRollBackTransactionOfPayment(session)).thenReturn(transaction);
when(transactionService.rollBackTransaction(transaction)).thenReturn(true);
sessionConfirmationJob.execute(ctx);
Assert.assertEquals(SessionStatus.FI, session.getStatus());
Assert.assertFalse(session.getPaymentConfirmation());
verify(sessionService).saveOrUpdate(session);
}
}
Before mock the Schedular object i get NullPointerException at pvs.addPropertyValues(context.getScheduler().getContext()); after i mock schedular it is solved and my test is passed. Below is the
org.springframework.scheduling.quartz.QuartzJobBean#execute(JobExecutionContext context) method. Actually executeInternal is protected so we must call execute method first then execute method is call executeInternal which is override at your implemented Job class(my demo it is SessionConfirmationJob).
QuartzJobBean.java
public abstract class QuartzJobBean implements Job {
/**
* This implementation applies the passed-in job data map as bean property
* values, and delegates to {#code executeInternal} afterwards.
* #see #executeInternal
*/
#Override
public final void execute(JobExecutionContext context) throws JobExecutionException {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValues(context.getScheduler().getContext());
pvs.addPropertyValues(context.getMergedJobDataMap());
bw.setPropertyValues(pvs, true);
}
catch (SchedulerException ex) {
throw new JobExecutionException(ex);
}
executeInternal(context);
}
/**
* Execute the actual job. The job data map will already have been
* applied as bean property values by execute. The contract is
* exactly the same as for the standard Quartz execute method.
* #see #execute
*/
protected abstract void executeInternal(JobExecutionContext context) throws JobExecutionException;
}
If you have question don't hesitate to ask me via comments.