私は内部でSpring AMQP接続オブジェクトを使用するサービスクラスをテストしようとしています。この接続オブジェクトはSpringによって注入されます。ただし、ユニットテストでAMQPブローカーと実際に通信したくないので、Mockitoを使用して接続オブジェクトのモックを挿入しています。
/**
* The real service class being tested. Has an injected dependency.
*/
public class UserService {
@Autowired
private AmqpTemplate amqpTemplate;
public final String doSomething(final String inputString) {
final String requestId = UUID.randomUUID().toString();
final Message message = ...;
amqpTemplate.send(requestId, message);
return requestId;
}
}
/**
* Unit test
*/
public class UserServiceTest {
/** This is the class whose real code I want to test */
@InjectMocks
private UserService userService;
/** This is a dependency of the real class, that I wish to override with a mock */
@Mock
private AmqpTemplate amqpTemplateMock;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testDoSomething() {
doNothing().when(amqpTemplateMock).send(anyString(), any(Message.class));
// Call the real service class method, which internally will make
// use of the mock (I've verified that this works right).
userService.doSomething(...);
// Okay, now I need to verify that UUID string returned by
// "userService.doSomething(...) matches the argument that method
// internally passed to "amqpTemplateMock.send(...)". Up here
// at the unit test level, how can I capture the arguments passed
// to that inject mock for comparison?
//
// Since the value being compared is a UUID string created
// internally within "userService", I cannot just verify against
// a fixed expected value. The UUID will by definition always be
// unique.
}
}
このコードサンプルのコメントで、質問が明確に示されることを期待しています。Mockitoがモックの依存関係を実際のクラスに挿入し、実際のクラスでユニットテストを実行してモックを呼び出した場合、注入されたモックに渡された正確な引数を後で取得するにはどうすればよいですか?
1つ以上ArgumentCaptor
のsを使用します。
あなたのタイプがここにあるかは不明ですが、とにかく。引数としてdoSomething()
a Foo
をとるメソッドを持つモックがあるとしましょう。そうすると、次のようになります。
final ArgumentCaptor<Foo> captor = ArgumentCaptor.forClass(Foo.class);
verify(mock).doSomething(captor.capture());
final Foo argument = captor.getValue();
// Test the argument
また、メソッドはvoidを返し、何も実行したくないようです。これを書いてください:
doNothing().when(theMock).doSomething(any());
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加