mock之InvalidUseOfMatchersException异常
新手小白对mock一知半解,就开始自测了,被这个InvalidUseOfMatchersException困扰了一晚上。排查了好久,大多数文章都把英文翻译了一遍,但自检无问题。最后发现是,注入的时候注解用成了@InjectMocks导致的,记录一下~
要开始补基础了,希望本文对你有所帮助~
- 异常信息
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:
-> at com.baidu.feed.hadoop.mr.bbs.schedule.strategy.BS60AssignWorkerForJobStrategyTest.testAssignWorkerResource(BS60AssignWorkerForJobStrategyTest.java:146)
-> at com.baidu.feed.hadoop.mr.bbs.schedule.strategy.BS60AssignWorkerForJobStrategyTest.testAssignWorkerResource(BS60AssignWorkerForJobStrategyTest.java:146)
-> at com.baidu.feed.hadoop.mr.bbs.schedule.strategy.BS60AssignWorkerForJobStrategyTest.testAssignWorkerResource(BS60AssignWorkerForJobStrategyTest.java:146)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
- 原因:
在mockgetDictMap
方法时,错误使用了@InjectMocks注解,导致了InvalidUseOfMatchersException异常
@InjectMocks
private DictPropertyService dictPropertyService;
......
when(dictPropertyService.getDictMap(anyString(),anyString(), anyString())).
thenReturn(oneJobStandardCoreMap);