【问题标题】:Does exist a way to verify with ArchUnit that any method doesn´t throw any exception?是否存在一种使用 ArchUnit 验证任何方法都不会引发任何异常的方法?
【发布时间】:2021-10-28 09:51:54
【问题描述】:

我想知道 ArchUnit 中是否存在避免方法签名引发任何已检查异常的方法。

【问题讨论】:

    标签: archunit


    【解决方案1】:

    您可以通过JavaMethod.getThrowsClause()(或JavaConstructor.getThrowsClause(),分别)访问代码单元声明的异常。

    以下使用custom condition 的规则禁止声明任何异常——如果您想排除RuntimeExceptions,您可以轻松地根据需要调整它:

    @ArchTest
    static ArchRule no_code_units_should_declare_exceptions = noCodeUnits()
        .should(new ArchCondition<JavaCodeUnit>("declare exceptions") {
           @Override
           public void check(JavaCodeUnit codeUnit, ConditionEvents events) {
             int nThrowsDeclarations = codeUnit.getThrowsClause().size();
             String message = String.format("%s has %d throws declarations in %s",
                 codeUnit.getDescription(), nThrowsDeclarations, codeUnit.getSourceCodeLocation()
             );
             events.add(new SimpleConditionEvent(codeUnit, nThrowsDeclarations > 0, message));
           }
        });
    

    【讨论】:

    • 是的,使用这种方式,您可以在任何包或整个模块中查看该选项。 @AnalyzeClasses(packages = "com.jab.microservices", importOptions = {ImportOption.DoNotIncludeTests.class})
    猜你喜欢
    • 1970-01-01
    • 2020-11-17
    • 2017-07-18
    • 2017-08-06
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多