【发布时间】:2014-12-07 22:27:27
【问题描述】:
我经常使用接受回调的方法,而回调似乎有点难以测试。让我们考虑下面的场景,如果有一个方法接受单个方法的回调(为简单起见,我假设测试方法是同步的),可以编写以下样板来确保调用回调方法:
@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,无论来自何处。但不幸的是,我已经使用回调的上下文提出了这个问题,但这只是一个选项,而不是要求。因此问题的标题并不能反映我真正想问的问题,但在更新之前已经发布了一些答案。
【问题讨论】:
标签: java unit-testing junit testng