Mocking an abstract class with a mocked constructor argument?

4,032 views
Skip to first unread message

Jeremy Johnson

unread,
Apr 16, 2012, 11:52:40 PM4/16/12
to moc...@googlegroups.com

[I originally posed this question on Stack Overflow, so please feel free to also copy your answer over there if you'd like to score the Stack Overflow reputation points.]

I'd like to use Mockito to unit test an abstract class as detailed in this great answer on Stack Overflow.

The trick is, the abstract class has a dependency on a strategy that gets injected in its constructor. I've created a mock of the strategy and I'd like for my mocked instance of BaseClass to use the mocked strategy for my unit test.

Any suggestion as to how I can wire this up? I'm not currently using any IoC framework, but am considering Spring. Perhaps it would do the trick?  

// abstract class to be tested w/ mock instance
abstract BaseClass
{
   
// Strategy gets mocked too
   
protected BaseClass( Strategy strategy)
   
{
       
...
   
}
}
Thanks!
Jeremy

Szczepan Faber

unread,
Apr 17, 2012, 3:49:05 AM4/17/12
to moc...@googlegroups.com
At the moment, the easiest way would be to expose some way for tests to set the strategy on the mock.

Down the road we probably need to figure out some API to create mocks using real constructors, with real parameters. The use case being spying on the abstract classes.

Cheers!

Jeremy

--
You received this message because you are subscribed to the Google Groups "mockito" group.
To view this discussion on the web visit https://groups.google.com/d/msg/mockito/-/5cgEPuMV9usJ.
To post to this group, send email to moc...@googlegroups.com.
To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mockito?hl=en.



--
Szczepan Faber
Principal engineer@gradleware
Lead@mockito

Eric Lefevre-Ardant

unread,
Apr 17, 2012, 3:48:52 AM4/17/12
to moc...@googlegroups.com
How about simply creating a local class in your test that inherits from your abstract class?

Jeremy

Szczepan Faber

unread,
Apr 17, 2012, 3:53:35 AM4/17/12
to moc...@googlegroups.com
Good idea. That's another simple solution.

Jeremy Johnson

unread,
Apr 17, 2012, 12:10:41 PM4/17/12
to moc...@googlegroups.com
Thanks guys!  I think I'm going to just use reflection to set a private field in my base class, like so:

        Strategy strategyMock = mock( Strategy.class);
        when(....).thenReturn(...);

        BaseClass baseMock = mock(BaseClass.class, CALLS_REAL_METHODS);
        baseMock.getClass().getSuperclass().getDeclaredField("_privateStrategy").set(baseMock, strategyMock);

        // do unit tests with baseMock
Reply all
Reply to author
Forward
0 new messages