Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - Mockito: How to match any enum parameter

I have this method declared like this

private Long doThings(MyEnum enum, Long otherParam); and this enum

public enum MyEnum{
  VAL_A,
  VAL_B,
  VAL_C
}

Question: How do I mock doThings() calls? I cannot match any MyEnum.

The following doesn't work:

Mockito.when(object.doThings(Matchers.any(), Matchers.anyLong()))
        .thenReturn(123L);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Matchers.any(Class) will do the trick:

Mockito.when(object.doThings(Matchers.any(MyEnum.class), Matchers.anyLong()))
    .thenReturn(123L);

null will be excluded with Matchers.any(Class). If you want to include null you must use the more generic Matchers.any().

As a side note: consider using Mockito static imports:

import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

Mocking gets a lot shorter:

when(object.doThings(any(MyEnum.class), anyLong())).thenReturn(123L);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...