Relating to this question, I have another question regarding unit testing functions in the utility classes:
Assume you have function signatures like this:
public function void doSomething(InternalClass obj, InternalElement element)
where InternalClass and InternalElement are both Classes which source code are not available, because they are hidden in the API. Additionally, doSomething only operates on obj and element. I thought about mocking those classes away but this option is not possible due to the fact that they do not implement an interface at all which I could use for my Mocking classes.
However, I need to fill obj with defined data to test doSomething.
How can this problem be solved?
Best Answer
What you are looking for is the adapter pattern: http://www.dofactory.com/Patterns/PatternAdapter.aspx
Using this pattern you can create a wrapper around the external class.
Lets take the following external class:
We can now easily create our own class as a wrapper around this external class, and Implement an interface:
}
This is our interface, which is implementing all the methods used in the external class. (If alot of methods are available, seperate the interfaces according to the Interface Segregation principle)
Now, when this Adapter class is used in your application instead of the external class, you should be able to mock any other implementation pretty easy.
You should never use non interfaced external classes in your code.
Pastebin link (since the code outlining is not working well here): http://pastebin.com/2qN7u3u6
If, for any reason, you also need a facade pattern... You can still wrap these 2 adapters in a single facade! But do not create a single facade on 2 external classes!