How to mock method with variable parameters concatenate(String... messages)
If I pass parameters as
String[] messages = {"abc"};
Helper helper = mock(Helper.class);
doReturn(someStr).when(helper).concatenate(messages);
It won't work.
How to mock method with variable parameters concatenate(String... messages)
If I pass parameters as
String[] messages = {"abc"};
Helper helper = mock(Helper.class);
doReturn(someStr).when(helper).concatenate(messages);
It won't work.
I honestly don't see the problem. Let's try it ...
Let's assume we have this class...
public class Helper {
public String concatenate(String...strings) {
// ...some concat logic, not important
}
}
...and now we want to mock it...
@Test
public void testSomething() {
Helper helper = Mockito.mock(Helper.class);
Mockito.doReturn("blablub").when(helper).concat(Mockito.anyVararg());
Assertions.assertThat(helper.concat("bla", "bli")).isEqualTo("blablub");
}
And yes, this works. We give it "bla" and "bli", but because we told the mock to return "blablub" in any case, we get that as result. So mocking any vararg is easy enough... We can of course also only check part of the whole vararg, for example...
Mockito.doReturn("blablub").when(helper).concat(Mockito.anyString(), Mockito.eq("blub"), Mockito.anyVararg());
Assertions.assertThat(helper.concat("bli", "blub", "bla", "blu", "blo")).isEqualTo("blablub");
...which will return "blablub" as long as then 2nd argument is "blub", no matter what the others are.
Better to use reflection method to initiate string value
FieldUtils.writeField(testClass, "stringVariableName", "value", true);