0

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.

NASK
  • 15
  • 3
  • Why whould you want to do something like that in the first place? – Mike Doe May 23 '17 at 11:47
  • 3
    Possible duplicate of [How to properly match varargs in Mockito](https://stackoverflow.com/questions/2631596/how-to-properly-match-varargs-in-mockito) – pvpkiran May 23 '17 at 11:49
  • @mike: I am writing junit using mockito and I want to mock concatenate(). I also tried Mockito.anyVararg() but no luck. – NASK May 23 '17 at 12:07

2 Answers2

0

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.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
-1

Better to use reflection method to initiate string value

FieldUtils.writeField(testClass, "stringVariableName", "value", true);