Skip to content

Inject and test JAVA method(or function) local variables with PowerMockito to make JUnit tests more

May 27, 2016

Ever had the situation when you really want to control the values of some of the local variables of the method you’re testing? Or want to assert the values of a JAVA method’s local variables that’s not returned (exposed) to the outside world? … Well, I just discovered this week that it’s all possible with the PowerMockito library.  Here attaches an example code snippet I wrote for my work. In the JUnit test( I forced the java “new Date()” call to always return day ‘0’ (1970-01-01) and verified the json object(also a local variable to the logUpdate method) has the eventTimestamp populated as expected – all thanks to the magic PowerMockito library 🙂

Date eventTimeStamp = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
JSONObject auditRow = new JSONObject();
auditRow.put("eventTimestamp", df.format(eventTimeStamp));
String input = auditRow.toString();

//Manipulate method's local variable values
Date mockDate = new Date(0); //Thu Jan 01 01:00:00 GMT 1970

//Hijack the method's local variable for testings
JSONObject injectedAuditObject = new JSONObject();



Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: