Let's say I have class A with
class A { final String foo() {
I now have class B with
class B { String methodIWantToTest(A a) { String output = a.foo();
How would I go for unit testing of this method? The reason foo() is final, because we do not want our classes to extend A to change its functionality. But at the same time a truly unit test method, I don't want it to stretch and run the actual A.foo() method.
Is there a way, say, to remove the last keyword and add annotation along the lines of @finalUnlessTest ? What would you suggest? Refactoring A to an interface would be very, very complex, as it was one of our central classes and, unfortunately, pretty was extremely connected.
Edit # 1 Sorry, forgot to mention, we are talking about Java. We do not use a mocking structure yet.
The answer is OK, so: wow. JMockit is just unbelievable and in my eyes a killer app for testing outdated code. Incredibly useful, especially in my case. Thanks! In my psuedo example, you would basically do something like the following:
class AMock { final String foo() { return "myTestValue"; } } class Test extends TestCase { A mockedA; B b; protected void setUp() { Mockit.redefineMethods( A.class, AMock.class );
Is this fricken cool or what?
java unit-testing mocking legacy-code
Epaga
source share