gpt4 book ai didi

java - Mockito 如何捕获传递给注入(inject)的模拟对象方法的参数?

转载 作者:IT老高 更新时间:2023-10-28 13:43:32 25 4
gpt4 key购买 nike

我正在尝试测试一个内部使用 Spring AMQP 连接对象的服务类。这个连接对象是由 Spring 注入(inject)的。但是,我不希望我的单元测试实际与 AMQP 代理通信,所以我使用 Mockito 注入(inject)连接对象的模拟。

/** 
* 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 将模拟依赖注入(inject)到真实类中,并且对真实类的单元测试导致它调用模拟时,您以后如何检索传递给注入(inject)模拟的确切参数?

最佳答案

使用一个或多个ArgumentCaptor

目前尚不清楚您的类型在这里,但无论如何。假设你有一个 mock,它有一个方法 doSomething()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());

关于java - Mockito 如何捕获传递给注入(inject)的模拟对象方法的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29169759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com