@Singleton
public class RealWorkWindow implements WorkWindow {
@Inject private Factory myFactory;
public RealWorkWindow (
LongSupplier longSupplier
) {
defaultWindow = myFactory.create(() -> 1000L);
workWindow = myFactory.create(longSupplier);
}
...
As you can see I am Injecting a factory class (injected via FactoryModuleBuilder)
Test code
@Test
public class RealWorkWindowTest {
private RealWorkWindow testWindow;
@BeforeMethod
void setup() {
MockitoAnnotations.initMocks(this);
testWindow = spy(new RealWorkWindow(() -> 1L));
}
Factory.py
public interface RealWorkWindowFactory {
RealWorkWindowFactory create(LongSupplier longSupplier);
}
Module
install(new FactoryModuleBuilder()
.implement(WorkWindow.class, RealWorkWindow.class)
.build(RealWorkWindowFactory.class));
When I run the test RealWorkWindowTest the test fails with NPE that factory does not exists, which makes sense since I dont think injection runs.
How can I test with Injection in junit? or mock properly?
Similar to the problem describe in https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html
But the problem that I have is that mock is used IN constructor so it's still a null when instantiate the test object (because i have not called Mockito.init yet)
If you use a MockitoJUnitRunner, you can use @Mock to create a mock for the Factory and inject it.
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@Mock
private Factory myFactory;
@InjectMocks
private RealWorkWindow realWorkWindow;
@Test
public void testSomething() {
when(myFactory.create(/* insert param here */)).thenReturn(/* insert return value here */);
/* perform your test */
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With