gpt4 book ai didi

Java 单元测试 : the easiest way to test if a callback is invoked

转载 作者:搜寻专家 更新时间:2023-10-30 21:40:53 24 4
gpt4 key购买 nike

我经常使用接受回调的方法,而回调似乎有点难以测试。让我们考虑以下场景,如果有一个方法接受单个方法的回调(为简单起见,我假设测试方法是同步的),可以编写以下样板文件以确保调用回调方法:

@Test
public void testMethod() {
final boolean[] passed = {false};
method(new Callback() {
@Override
public void handle(boolean isSuccessful) {
passed[0] = isSuccessful;
}
});
assertTrue(passed[0]);
}

它看起来像一个代理人。我想知道:是否有更优雅的方法来测试这样的代码,使上面的代码看起来更像下面的伪代码?

@Test
public void testMethod() {
// nothing explicit here, implicit boolean state provided by a test-runner
method(new Callback() {
@Override
public void handle(boolean isSuccessful) {
if ( isSuccessful ) {
pass(); // not sure how it should look like:
// * an inherited method that sets the state to "true"
// * or an object with the pass method
// * whatever
// but doesn't exit testMethod(), just sets the state
}
}
});
// nothing explicit here too:
// test runner might check if the state is changed to true
// otherwise an AssertionError might be thrown at the end of the method implicitly
}

稍微干净一点。在 JUnit、TestNG 或任何其他测试框架中是否可行?谢谢!


更新

对不起,我好像问了一个模糊的问题,并不能真正满足我想问的问题。我的意思基本上是指在满足某些条件时可能调用的任何代码(不一定是回调),只是为了将结果状态设置为 true。简单来说,我只是想摆脱最初的 boolean[] passed 和最后的 assertTrue(passed[0]) 假设它们是某种序言和结语分别假设初始状态设置为 false,因此应调用 pass() 将状态设置为 true。无论 如何 passed[0] 设置为 true,无论来自何处。但不幸的是,我已经使用回调的上下文问过这个问题,但这只是一个选项,而不是必需的。因此问题的标题并没有反射(reflect)我真正想问的问题,但在更新之前已经发布了一些答案。

最佳答案

这通常是模拟框架可以为您做的。

Mockito例如:

// imports ommited for brevity
@Test
public void callbackIsCalled()
{
final CallBack callBack = mock(CallBack.class);
method(callBack);

verify(callBack, only()).handle(any());
}

当然,这是验证模式(only())和值匹配器(any())的例子。你可以做更多...

(存在其他模拟框架,但我个人认为 Mockito 最容易使用,而且是最强大的框架之一)

关于Java 单元测试 : the easiest way to test if a callback is invoked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348625/

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