In the end, I just used reflection to set a private field in my base class, for example:
// mock the strategy dependency Strategy strategyMock = mock( Strategy.class); when(....).thenReturn(...); // mock the abstract base class BaseClass baseMock = mock(BaseClass.class, CALLS_REAL_METHODS); // get the private streategy field Field strategyField = baseMock.getClass().getSuperclass().getDeclaredField("_privateStrategy"); // make remove final modifier and make field accessible Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(strategyField, strategyField.getModifiers() & ~Modifier.FINAL); strategyField.setAccessible(true); // set the strategy strategyField.set(baseMock, strategyMock); // do unit tests with baseMock ...
It will break if the name of the private field has ever changed, but commented on it, and I can live with it. This is a simple, one line of code, and I find it preferable to expose any setters or have an explicit subclass in my tests.
Edit: So this is not a single line of code, since my personal field should be "final", which requires an additional reflection code.
source share