Working with Mock Objects, Thomas Schneider (March, 2007)

1. Introduction

To test an external service that is at the moment not available, it is common to use mock objects. This objects are simple objects, implementing service interfaces in a testing manner. To implement such interfaces, see the paper 'generic interface implementation'. This paper describes, how to work with mocking error-handling, using a swing user interface. In a lot of cases, you have to handle errors, influenzing the workflow. In your mocking implementations, you would like to simulate these errors (exceptions) to test all cases. In the next chapter I will show a simple, interactive way to simulate exception throwing.

2. Handling Exceptions in Mock Objects

In some cases, you have a method of this type:
Inside the try block, we wish to have the option, to decide where to go to. So we call a simple method throwOptionalException(...), before the goto step x. This throwing method could be:

options = new Object
"No Error", "MyException1", "MyException2"; int selected = JOptionPane.showOptionDialog( null, "Please select an Exception to throw!", "MockingObjectRuntimeConfigurator", 0, JOptionPane.QUESTION_MESSAGE, null, options, options0
); switch (selected) { case 0: //No Error return; case 1: //MyException1 throw new MyException1(); case 2: //MyException2 selectedElement.set...(...); throw new MyException2(); } } ]]>
There is no other way to do that, because special exceptions have to be thrown. Reflection is no solution. If you try to find a generic way with reflection, your special exceptions will be packed into an InvocationTargetException including the real exception inside the cause attribute.
Working with Mock Objects
1