svs teja
svs teja

Reputation: 1027

Unit Testing Scheduler job in java

We have a cron based job in our application.

The job class is as follows:

       public class DailyUpdate implements Job {

        public void execute(JobExecutionContext context) throws JobExecutionException {
                SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

testMethod();

}
        private void testMethod()
        {
System.out.pritnln("Executed From scheduler");
        }
        }

How should we write unit test case to test Method testMethod()

I cannot call testMethod Directly without scheduler as it is private..Any suggestion how to write unit test cases for Scheduler

Upvotes: 0

Views: 7020

Answers (2)

Akah
Akah

Reputation: 1920

If you have the opportunity, I would suggest you to use PowerMock (instead of coding it by yourself). Here is a link explaining how to use it : How to mock private method for testing using PowerMock?

Upvotes: 0

Alexius DIAKOGIANNIS
Alexius DIAKOGIANNIS

Reputation: 2584

In order to write a test you need to have an expected behavior so there is no point on testing a method that does nothing.

Now to your main problem. If you have somewhat of a legacy application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.

So you can use the following pattern

Method testMethod = DailyUpdate.getDeclaredMethod(testMethod, argClasses);
testMethod .setAccessible(true);
return testMethod.invoke(targetObject, argObjects);

see also this question how to test a class that has private methods fields or inner classes

Upvotes: 1

Related Questions