首页 > 解决方案 > 如何避免在 kotlin 中使用繁琐的 holder

问题描述

我必须处理以下java代码

abstract class ScriptResult {
    void ifSuccess(Consumer<Object> block) {
    }

    void ifError(Consumer<Throwable> block) {
    }

    static class Success extends ScriptResult {
        private final Object returnValue;

        Success(Object returnValue) {
            this.returnValue = returnValue;
        }

        @Override
        void ifSuccess(Consumer<Object> block) {
            block.accept(returnValue);
        }
    }

    static class Error extends ScriptResult {
        private final Throwable throwable;

        Error(Throwable throwable) {
            this.throwable = throwable;
        }

        @Override
        void ifError(Consumer<Throwable> block) {
            block.accept(throwable);
        }
    }
}

我的 kotlin 测试使用以下断言助手:

private lateinit var scriptResult: ScriptResult

inline fun <reified T : Throwable> shouldHaveThrown(): T {
    scriptResult.ifSuccess { result ->
        fail("should have thrown ${T::class.java.name}, but returned `$result´")
    }
    lateinit var holder: T // (1)
    scriptResult.ifError { throwable ->
        if (throwable is T) {
            holder = throwable // (2)
        } else {
            fail("expected ${T::class.java.name} to be thrown, but threw `$throwable´")
        }
    }
    return holder // (3)
}

断言助手是有效的。我可以这样使用它:

    val thrown = execution.shouldHaveThrown<MissingMethodException>()
    assertThat(thrown.message).contains("missedMethod")

但我怀疑有一种更惯用的方式来返回throwableshouldHaveThrown然后返回(1)声明持有者,(2)分配它,(3)最终返回它。如何?

标签: kotlin

解决方案


推荐阅读