samedi 26 septembre 2015

Can JMockit MockUp mock toString()?

Consider the following sample MockUp of a class Foo that intercepts Bar in the constructor and then implements toString() in terms of Bar;

public class FooStub extends MockUp<Foo> {

    private Bar bar;

    @Mock
    public void $init(Bar bar) {
        this.bar = bar;
    }

    @Mock
    public String toString() {
        return bar.toString();
    }
}

If Foo happens to override toString() all works fine. Otherwise though, you get a IllegalArgumentException : "Matching real methods not found for the following mocks". I understand from here that JMockit does not look in base classes and therefore cannot find a toString() method to mock.

Assuming I can't modify the Foo class (in reality I can, but just for the sake of argument), is there any way to mock toString() just for this Foo class?

To be clear, I want to mock all instances of this class, not just one instance (that has easy solutions that do no require a MockUp).

Aucun commentaire:

Enregistrer un commentaire