Created
October 6, 2020 15:17
-
-
Save netstart/d44b46534df72c84b0957c94677d92ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package matera.spi.messaging; | |
import org.mockito.Mockito; | |
import java.lang.reflect.Field; | |
/** | |
Example to use: | |
<PRE> | |
new Injector<MessageValidator, Message>() | |
.injectMock(MessageValidator.class) | |
.in(new Message()) | |
.on("messageValidator"); | |
</PRE> | |
After each test may be you need clean and reset mock object like this: | |
<PRE> | |
@AfterEach | |
public void afterEach() { | |
Mockito.reset(this.messageValidator); | |
Mockito.clearInvocations(this.messageValidator); | |
} | |
</PRE> | |
*/ | |
public class Injector<C, I> { | |
Class<C> inject; | |
I in; | |
public Injector<C, I> injectMock(Class<C> inject) { | |
this.inject = inject; | |
return this; | |
} | |
public Injector<C, I> in(I in) { | |
this.in = in; | |
return this; | |
} | |
public C on(String fieldName) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { | |
Field field = in.getClass().getDeclaredField(fieldName); | |
field.setAccessible(true); | |
C mocked = Mockito.mock(inject); | |
field.set(in, mocked); | |
return mocked; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment