Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to go about mocking a class with final methods?
    text
    copied!<p>Say I have class A with</p> <pre><code>class A { final String foo() { // .. computing result, contacting database, whatever .. return "some computed value"; } // ... and a bazillion other methods, some of them final. } </code></pre> <p>Now I have class B with</p> <pre><code>class B { String methodIWantToTest(A a) { String output = a.foo(); // ... whatever this method does, e.g.: output += "_suffix"; return output; } } </code></pre> <p>How would I go about unit testing this method? The reason <code>foo()</code> is final is because we don't want our classes which extend A to change its functionality. But at the same time to truly unit test the method, I don't want it to reach out and run the actual <code>A.foo()</code> method.</p> <p>Is there a way to, say, remove the final keyword and add an annotation along the lines of <code>@finalUnlessTest</code>? What would you recommend? Refactoring A to an interface would be very, very difficult, seeing as how it's one of our central classes and is unfortunately <s>pretty</s> extremely coupled.</p> <p><strong>Edit #1</strong> Sorry, forgot to mention, we're talking Java. We are not using a mocking framework as of yet.</p> <p><strong>Answer</strong> OK, so: wow. <a href="http://jmockit.org" rel="nofollow noreferrer">JMockit</a> is just incredible and is in my eyes the killer app for testing legacy code. Unbelievably useful especially in my case. Thanks so much! You basically would do something like the following for my psuedo-example:</p> <pre><code>class AMock { final String foo() { return "myTestValue"; } } class Test extends TestCase { A mockedA; B b; protected void setUp() { Mockit.redefineMethods( A.class, AMock.class ); // this "pipes" all mocked methods from A to AMock mockedA = new A(); // NOT new AMock()!!! b = new B(); } public void testB() { assertEquals("myTestValue",mockedA.foo()); assertEquals("myTestValue_suffix",b.methodIWantToTest(mockedA)); } } </code></pre> <p>Is this frickin' cool or what?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload