I am writing a junit testcase that tests a class, A, that uses a very complex class, B. I would like to create a mock object that will replace B and will be used when I run my junit test case instead of using the very complex B class. The problem is that I can not change the code in the class that I am testing. So I have to name my mock object the same as the complex class. When I create the mock object, B, I am naming it the same, but I am putting it into a different directory. In Eclipse I am getting the error, "The type B is already defined".
The first answer is: What's the point of testing something if you cannot change it to fix any problems you find? Are you really sure you cannot change the class, even to add an extra constructor which is never used by the "real" code, for example?
The second answer is that you can make Eclipse do this, but you will need to get fairly creative with classpath settings. The trick is to have two areas of your source code, one of which is in the classpath for the application code, and one of which is in the classpath for the tests.
I don't know how you build whatever is actually delivered, but if you use Ant, then it is pretty easy to set different classpaths for different operations. If that is the case, then you should be able to remove the "real" class from the Eclipse build path settings, so Eclipse (and thus the built-in JUnit) only "sees" your mock version.
The third answer is that the difficulty of this is a strong "code smell" that these classes need to be decoupled.
I am the poor sap that has come along six months after the project was finished and told to write junit testcases for existing code. The code stinks to high heaven. It is a huge application written by a large company and it is possible to get approval to promote unit test code that will not be executed in production, but it takes an act of god to make changes to production code. This is why I can't modify the actual class I am testing, at least until the next release goes in which will be some time next year. So I am going to try and figure out how to change the class path for just my junit test execution. I can't change production build scripts either.
I am displeased. You are no longer allowed to read this tiny ad: