1

While I was writing some unit test, I came to a point when I needed to instrument a mock to return a given result if the input parameter was a not empty list. It was not essential to know which values the list stores. The only important thing is that it is not empty.

I am using Mockito, and I am searching for something like the following.

when(mock.someMethod(anyNotEmptyList(String.class))).thenReturn(42);

I googled a little, but I cannot find anything.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
riccardo.cardin
  • 7,971
  • 5
  • 57
  • 106

2 Answers2

2

You could do that with Mockito Answer without using Harmcrest :

 when(mock.someMethod(anyListOf(String.class)))
.then(invocation -> { 
                      List<String> list = invocation.getArgument(0);
                      return list.size() > 0 ? 42 : null;
                    }
 );

Here I specify null as default value that is the default return for a method invoked on a Mock (without considered nice values of course).

davidxxx
  • 125,838
  • 23
  • 214
  • 215
1

According to the duplicate I commented, you should try:

class IsAtLeastOneElementList extends ArgumentMatcher<List<String>> {
    public boolean matches(Object list) {
        return ((List) list).size() > 0;
    }
}
riccardo.cardin
  • 7,971
  • 5
  • 57
  • 106
aBnormaLz
  • 809
  • 6
  • 22
  • 1
    Don't copy answers from a duplicate question. You've flagged the question as a dupelicate and that's all you need to do. – Tom Jan 21 '19 at 09:54
  • As it turned out it wasn't really a duplicate, and i didn't just copy the question, but answered it. I didn't know it's not the good way to use Stackoverflow, so thanks for your feedback – aBnormaLz Jan 21 '19 at 10:28
  • It is a duplicate. The "other" question doesn't need to ask the same question, it only matters if the answers there also answer the question here. This is the case here, like Riccardo said in one of the comments. This question here would then work like a sign post for other people to be directed to the other question where their wanted answer is. – Tom Jan 21 '19 at 10:30
  • i don't know much about reputations, but I think you can close it as a duplicate with 9000 points, don't you? – aBnormaLz Jan 21 '19 at 10:41
  • 1
    I can vote to close it. A question needs 5 votes to be closed. You already flagged it (a flag is not the same as a vote), so others can review and then vote to close it if they agree. (you need 3000 points to cast such vote). – Tom Jan 21 '19 at 12:03