I want to use mockito for mocking the constructor call when a specific argument is passed.
Lets say this is my class -
public class MyTestClass {
private final String argument;
public MyTestClass(String argument) {
this.argument = argument;
}
}
now suppose there is a test which calls
MyTestClass object = new MyTestClass("abcd");
now I want to mock the constructor call using mockedConstruction such that when "abcd" is passed as argument then return mockObject.
I tried this way -
public void setUp() throws Exception {
try (MockedConstruction<MyTestClass> mockConstruction = Mockito.mockConstruction(MyTestClass.class, (mock, context) ->{
if(context.arguments().get(0).equals("abcd")){
mock = mockObject;
} )
{
}
}
But this is not working as expected. Please help me correct my code, I am beginner.
mock = mockObject;
- that's definitelly not going to work, read Is Java "pass-by-reference" or "pass-by-value"? Instead configure the mock -when(mock.someMethodCall()).thenReturn(something)
.