Stubs versus the proxy pattern

For my employer I’m currently writing a course of design patterns, which I will give this year to a group of my colleagues. Therefore I was looking at the various design patterns that could be interesting for the people to learn. When I prepare such a course, I try to think what kind of thinking errors the students could make. When you do this, you can deep out your story much more and anticipate on questions that can arise.


When I was working on the proxy pattern, I also found something some people could interprent wrong. Lets first have a look at the proxy pattern. Within the proxy pattern, we replace the instance we normally would invoke with a so-called proxy. This proxy implements the same interface as the object before. Calls within our application, which would run to the old instance will now go via the proxy. The proxy instance then calls the original method on the replaced object. Below you can find the UML diagram of the proxy pattern.

UML diagram of the proxy pattern

At first you might think the proxy pattern is used the same way we use stubs within unit tests: replace an object you’re calling with another implementation. This new implementation will now react on the calls you’re performing on it. However, the big difference between how we use stubs and how the proxy pattern is used, is the fact how the proxy (or stub) deals with the received calls. By use of stubs, the call of the our so-called subject is answered with a default answer of the stub. By use of the proxy pattern, the proxy will redirect the call to the RealSubject. This redirection is a really great difference compared with a stub. If we would stub some piece of hardware, by using the proxy pattern, the call would be redirected to the hardware via the proxy. Calling the real hardware is exactly the thing we want to prevent by stubbing it.

Posted in Design patterns, Unit testing by Bruno at January 20th, 2014.

Leave a Reply