views:

559

answers:

4

Let's say you have some 3rd-party library class that you want to extend, simply to add convenience methods to it (so you can call an inherited method with default parameters for example).

Using jUnit/jMock, is it possible to write an assertion / mock expection that tests that the correct inherited method is called?

For example, something like this:

class SomeClass extends SomeLibraryClass {
    public String method(String code) {
         return method(code, null, Locale.default());
    }
}

How can I assert that method is being called?

+1  A: 

You can make a further subclass inside your unit test that actually tells you:

public class MyTest {
    boolean methodCalled = false;

    @Test
    public void testMySubclass(){
          TestSomeClass testSomeClass = new TestSomeClass();
          .. invoke method on testSomeclass ..
          aseertTrue( methodCalled);

    }  
    class TestSomeClass extends SomeClass{
        public String method(String code){
              methodCalled = true;
        } 
     }
}
krosenvold
Won't this just tell you if your test subclass overwrote the method, not if your "real" subclass overwrote the method? This test will pass even if your "real" subclass didn't overwrite the method.
killdash10
+2  A: 

Unit testing is more useful to verify the functionality of given methods, not to assert coverage. Unit tests that care more about what method got called know way more about the classes they are testing than they probably should, not to mention will be confusing to the reader.

Coverage tools like Cobertura or EMMA will tell you whether you properly covered your code.

Nick Veys
I understand your point, the problem is that this method has no functionality except to call the parent method with the correct signature.
TM
If the method has no functionality, why is it there? The unit test should assert what a user would expect to happen when the method is called.
Nick Veys
I see from your above comment and re-reading your initial post that this is wrapping a 3rd party library? My bad for missing that, that is somewhat more unique in scope.
Nick Veys
A: 

it's hard to tell without a more concrete example, but I'd guess that this ought to be an integration test--test the whole package together--rather than a unit test. Sometimes one can be too fine-grained with unit testing.

Steve Freeman
A: 

It may indeed be better to only write integration tests in this case, but if you really want a unit test, you can have it just as easily as in any other case:

public class SomeClassTest
{
    @Test
    public void testMethod()
    {
        final String code = "test";

        new Expectations()
        {
            SomeLibraryClass mock;

            {
                mock.method(code, null, (Locale) any);
            }
        };

        new SomeClass().method(code);
    }
}

This test uses the JMockit mocking API.

Rogerio