使用mockito模拟异步(@Async
)方法的最佳方法是什么?以下提供的服务:如何在使用Mockito的Spring Boot中模拟异步(@Async)方法?
@Service
@Transactional(readOnly=true)
public class TaskService {
@Async
@Transactional(readOnly = false)
public void createTask(TaskResource taskResource, UUID linkId) {
// do some heavy task
}
}
的Mockito的验证如下:
@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
private TaskService taskService;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
// other details omitted...
@Test
public void shouldVerify() {
// use mockmvc to fire to some controller which in turn call taskService.createTask
// .... details omitted
verify(taskService, times(1)) // taskService is mocked object
.createTask(any(TaskResource.class), any(UUID.class));
}
}
上述试验方法shouldVerify
总会抛出:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:
-> at SomeTest.java:77) // details omitted
-> at SomeTest.java:77) // details omitted
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.
如果我删除@Async
上述异常不会happend从TaskService.createTask
方法。
春天启动的版本:1.4.0.RELEASE
版本的Mockito:19年1月10日
您能否提供您的测试的整个实施。具有方法createTask的类是否是超级类? – marians27
嗨Marians27,我编辑了这个问题。重要的一点是,如果我从TaskService类中删除@Async注释,则不会发生异常。 –
'@Async'注释是否会导致aspectj或其他东西被踢入?你确定,你试图验证的'taskService'实例没有被任何方面或类似的东西修改吗? – SpaceTrucker