Reputation: 117
I essentially have a main class that uses interfaces to call other classes which contain members. I am supposed to mock the interfaces that this (concrete) main class uses to call the other classes. The purpose of this is to create a mocked getMember() method for these other classes that would be cumbersome to implement. We only need to ensure, for now, that the main class behaves as expected, given certain return values from the getMember() method.
The only way I see this being possible right now is by passing mock instances of the classes that implement those interfaces.
I'm very sorry if this seems like a stupid question, but I just cannot find an answer to my question by reading this assignment, documentation or via search engines.
Upvotes: 3
Views: 5718
Reputation: 750
Try this:
AnInterface anInterfaceMock = Mockito.mock(AnInterface.class);
//Set your properties here if you want return an specific object.
Member member = new Member();
Mockito.when(anInterfaceMock.getMember()).thenReturn(member);
YourMainClass yourMain = new YourMainClass();
yourMain.setAnInterfaceMock(anInterfaceMock);
yourMain.testMethod(); // call the method you wan to test. This method internal implementation is supposed to call anInterfaceMock.getMember()
Mockito.verify(anInterfaceMock).getMember();
UPDATE: After the info about the main class not having a way to force the chose interface to mock, it seems like a work to PowerMockito. But posting the code of your main class would help a lot.
Upvotes: 4
Reputation: 914
Is it your main class that creates the instances of its dependencies (that implement those interfaces that you mentioned)? If possible you'd better change the main class to follow the Dependency Injection pattern. Then you'll supply our main class with its dependencies via constructor or via setters. Those dependencies can be mocks for testing or the true implementations in the production code.
Modifying the guilhermerama's example a bit.
YourMainClass yourMain = new YourMainClass(anInterfaceMock);
Upvotes: 1