非同期(@Async
)メソッドをmockitoでモックする最善の方法は何ですか?下記の提供するサービス:Mockitoを使ってSpringブートで非同期(@Async)メソッドをモックする方法は?
@Service
@Transactional(readOnly=true)
public class TaskService {
@Async
@Transactional(readOnly = false)
public void createTask(TaskResource taskResource, UUID linkId) {
// do some heavy task
}
}
Mockitoの検証以下のように:試験方法上記shouldVerify
@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));
}
}
は常にスローされます。
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
を削除する場合は、上記の例外が起こっていないだろう方法はTaskService.createTask
です。
春ブートバージョン:1.4.0.RELEASE
Mockitoのバージョン:1.10.19
テストの実装全体を提供できますか? createTaskメソッドを持つクラスはスーパークラスですか? – marians27
こんにちはMarians27、私は質問を編集しました。重要な点は、@AsyncアノテーションをTaskServiceクラスから削除すると例外が発生しないことです。 –
'@ Async'アノテーションはaspectjや何か他のものを引き起こしますか?あなたが確認しようとしている 'taskService'インスタンスがどんな面でも変更されていないことは確かですか? – SpaceTrucker