I’m using Java 6 with JUnit 4.8.1 (and Maven 3.0.3). For certain JUnit tests, I want to replace a class that some of the tests are dependent on (qualified as com.myco.clearing.product.server.cache) with my own version of this class (which has the same public method signatures). What is an elegant way to do this?
Note that some of the JUnit tests don’t invoke the com.myco.clearing.product.server.cache.Cache class directly, but rather call classes that rely on this class. Even in these indirect cases, I want my version of the class to be used.
Thanks for any help along these lines, – Dave
It is hard to say exactly what to do here, but in general:
Use some IoC techniques – contructor, setter injection.
Use a mocking framework to mock your objects, I would recommend
Mockito.
So, for example, if you have a class that uses
com.myco.clearing.product.server.cache.Cachelet’s call itFoo. And you use now like this:If possible, change it to something like this:
Then you may be able to inject in a mocked version of the
Cacheclass. I say “may be able to” as it depends on theCacheclass. If it is final, has a bunch of static methods, etc. then you have more to deal with.