Я пытаюсь протестировать класс сервиса, который внутренне использует объект соединения Spring AMQP. Этот объект соединения вводится Spring. Тем не менее, я не хочу, чтобы мой unit test фактически связывался с брокером 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 вводит ложную зависимость в настоящий класс, а модульные тесты в реальном классе заставляют его совершать вызовы макета, как вы можете позже получить точные аргументы, которые были переданы в инцессионный макет?