Mockito: How to mock javax.inject.Provider-created prototype beans?
I would stub that Provider
and make it return the prototypeMock
every time using the @Before
method invoked before each of the tests:
@Mock
private javax.inject.Provider<MyPrototype> prototypeFactoryStub;
@Mock
MyPrototype prototypeMock;
@InjectMocks
MySingleton sut;
@Before
public void init(){
MockitoAnnotations.initMocks(this); // optional
when(prototypeFactoryStub.get()).thenReturn(prototypeMock);
}
@Test
public void testPrototype() {
sut.doStuff();
verify(prototypeMock, times(1)).invoke();
}
I have written an article on Mockito Stubbing if you need a further read.