Reputation: 1180
I'm using mokito to inject a mock. This object extends a class that requires a contructor with arguments. How to mock this object that requires constructor arguments and pass this arguments as mock too?
Example class
public abstract class AbstractClassRequireContructor{
protected AbstractClassRequireContructor(Object param) {
}
public class ClassA extends AbstractClassRequireContructor{
public ClassA(Object param) {
super(param); // required by super class
}
}
Test class
@ExtendWith(MockitoExtension.class)
public class ClassATest{
@Mock
private Object paramMockToBeAddedByConstructor;
@InjectMocks
private ClassA classA; // requires contructor from super class
@BeforeEach
void setup{
when(paramMockToConstructor.anyMethod()).thenReturn(anyValue);
// how to inject mocked argument?
classA = new ClassA(paramMockToBeAddedByConstructor); // this doesn't work
}
@Test
void test(){
when(classA.anyMethod()).thenReturn(anyValue); // use injectMock class normally
}
}
Is there any another strategy to work arroung this better?
Upvotes: 0
Views: 597
Reputation: 17510
Drop the instantiation of a new ClassA
object. It should work without it as follows:
@ExtendWith(MockitoExtension.class)
public class ClassATest{
@Mock
private Object paramMockToBeAddedByConstructor;
@InjectMocks
private ClassA classA;
@BeforeEach
void setup{
when(paramMockToConstructor.anyMethod()).thenReturn(anyValue);
}
@Test
void test(){
when(classA.anyMethod()).thenReturn(anyValue);
}
}
Upvotes: 0