【问题标题】:Is it possible to check if method is declared in a group of classes?是否可以检查方法是否在一组类中声明?
【发布时间】:2021-01-18 13:14:54
【问题描述】:

我正在使用 ArchUnit,我想检查一个包中的所有类是否都声明了一个名为 execute 的唯一公共方法。我有这个代码:

JavaClasses importedClasses = new ClassFileImporter().importPackages("my.package");        
methods().that().arePublic().should().haveName("execute").check(importedClasses);

它有效,但我希望这个测试在任何类中都没有 execute 方法时失败。使用我的代码,测试通过,因为所有公共方法(零)实际上都有名称“执行”。

【问题讨论】:

  • this answer 解决了您的问题吗?如果是这样,最好将其标记为已接受,否则您的问题仍然显示为未回答。

标签: java unit-testing archunit


【解决方案1】:

为了测试类,您必须将ArchRule 基于它们(而不是基于可能不存在的方法)。您可以使用custom condition 来计算公共方法并测试它们的名称,例如像这样:

ArchRule rule = classes()
    .that().resideInAPackage("my.package")
    .should(new ArchCondition<JavaClass>("have exactly one public method named 'execute'") {
        @Override
        public void check(JavaClass javaClass, ConditionEvents events) {
            List<JavaMethod> publicMethods = javaClass.getMethods().stream()
                    .filter(javaMethod -> javaMethod.getModifiers().contains(PUBLIC))
                    .collect(toList());
            boolean satisfied = false;
            String message = javaClass.getName() + " contains " + publicMethods.size() + " public method";
            if (publicMethods.size() == 1) {
                JavaMethod method = publicMethods.get(0);
                satisfied = method.getName().equals("execute");
                message += " named '" + method.getName() + "' " + method.getSourceCodeLocation();
            } else {
                message += "s " + javaClass.getSourceCodeLocation();
            }
            events.add(new SimpleConditionEvent(javaClass, satisfied, message));
        }
    });

【讨论】:

    猜你喜欢
    • 2015-08-19
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-07-16
    • 1970-01-01
    相关资源
    最近更新 更多