gpt4 book ai didi

java - Mockito - 监视多个依赖项

转载 作者:行者123 更新时间:2023-12-01 17:01:10 25 4
gpt4 key购买 nike

是否可以将两个依赖项的 spy 注入(inject)到被测试的类中?我有这门课:

@Service
@Singleton
@MessageReceiver
public class LinkHitCallbackEventHandler {
public static final Logger logger = LogManager.getLogger();

@Inject
private CallbackInvocationBuilder callbackInvocationBuilder;

@Inject
private CallbackLogBuilder callbackLogBuilder;

@MessageReceiver
public void handle(@SubscribeTo LinkHitEvent event) {
Entity<Form> entity = EntityFormFactory.createFromEvent(event);

this.callbackLogBuilder.build(entity);

Response response = this.callbackInvocationBuilder.post(entity);
}
}

重要的是,它是一个简单的类,具有两个注入(inject)的依赖项:callbackIn VocationBuildercallbackLogBuilder

我通过以下方式测试对这些依赖项的调用:

    @Test
public void send_callback_after_event_is_published() {
target("/testY")
.property("jersey.config.client.followRedirects", false)
.request()
.header("User-Agent", UserAgentMother.allowedUserAagent())
.get();

verify(callbackInvocationBuilder).post(anyObject());
// verify(callbackLogBuilder).build(anyObject());
}

这种安排测试通过了,因为我首先调用了callbackLogBuilder.build(entity)

如果我交换调用并首先调用它们callbackInvocalBuilder.post(entity),测试将失败。

callbackLogBuilder 和callbackInvocationBuilder 都是 spy 。我在 JerseyTest 的 configure() 中配置它们。以完全相同的方式。

最佳答案

注入(inject) spy 的方法之一是使用whitebox并使用verify

像这样:

Whitebox.setInternalState(ClassToTest.class, "Object", spy1);

,所以测试方法会是这样的:

    @Test
public void send_callback_after_event_is_published() {
Whitebox.setInternalState(LinkHitCallbackEventHandler.class, "callbackInvocationBuilder", spy1);
Whitebox.setInternalState(LinkHitCallbackEventHandler.class, "callbackInvocationBuilder", spy2);

target("/testY")
.property("jersey.config.client.followRedirects", false)
.request()
.header("User-Agent", UserAgentMother.allowedUserAagent())
.get();

verify(callbackInvocationBuilder).post(anyObject());
verify(callbackLogBuilder).build(anyObject());
}

, 如果你想捕获参数

ArgumentCaptor<Entity> captor = ArgumentCaptor.forClass(Entity.class);
verify(callbackInvocationBuilder, times(1)).post(captor.capture());

Entity actualEntity = captor.getValue();
assertEquals(expected, actualEntity);

关于java - Mockito - 监视多个依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61505418/

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