Mocking is a subject extensively covered and used heavily in Unit Testing. There are number of Mocking frameworks available today, ranging from Static Mocking to Dynamic Mocking, and the latest additions are AOP based Mocking Frameworks. Had been Coding for a few years now and at that time, JUnit has just made its entry. Wow! now I can automate my Unit Testing, but the pain was had to use static mock, objects. Each time I needed a new Object State, had to recompile and test again.
This is how a static mock code looks like
Even when using a mocking framework, we have to define the state of the object we want to return, which means compiling and redploying especially when testing deployed applications. Can frameworks be smart enough to take care of all data variation? unfortunately, the answer is no. Frameworks provide various ways of reducing the effort, but can’t make it zero. Hope its always true, else Develoeprs like me shall loose their jobs.
Coming back to the topic. With a little overhead we can make this mock dynamic, so that we can change the state of the object without compiling and redeplying 🙂
Let me introduce beanshell. Beanshell is a framework that supports lightweight scripting in Java and it now JSR274. It allows to write scripts in Java syntax, with type relaxation. Now lets see how can we make out Status mock, a dynamic mock by using beanshell script. many IDE’s support beanshell scripting as well. Other options available are JRuby and Groovy.
Lets change the Mocked Object code to support beanshell
We create an instance of BSH Interpreter and call the file containing the implementation of the function. I prefer seperate file for seperate functions, to have exercise more control. The difference here is, we have moved the main logic from compiled code to interpreted code. This way, we can change the logic at runtime. We just change the bsh file and the interpreter executes the new version.
Lets look at bsh file
This post displays the cocnept in a very simplistic manner. There can be many variations like implementing the interfaces completely in scripting. Scripting can used as an add-on to existing mocking frameworks taking the Unit Testing to next level.