Mockito如何捕获传递给注入模拟对象的方法的参数?
2022-08-31 20:28:12
我正在尝试测试一个服务类,它在内部使用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 将模拟依赖项注入到真实类中,并且对真实类的单元测试导致它对模拟进行调用时,您以后如何检索传递给注入模拟的确切参数?