使用Archunit对方法调用进行检查
Archunit是一个Java静态代码分析库,它可以用来检查代码结构和规范。其中之一的功能是检查方法调用。为了使用Archunit检查方法调用,请按照以下步骤操作:
1.添加Maven依赖项
    com.tngtech.archunit 
    archunit-core 
    0.12.0 
 
2.编写单元测试
public class MyTest {
    private static final JavaClasses classes = new ClassFileImporter()
        .importPackages("com.example.myapp");
    @Test
    public void testMethodCalls() {
        ArchRule rule = prioritizesSomeMethods()
            .as("priority methods should be called before non-priority methods");
        rule.check(classes);
    }
    private ArchRule prioritizesSomeMethods() {
        return ArchRuleDefinition.methods()
            .that().haveNameMatching(".*(doSomething|doAnotherThing).*")
            .should().beCalledBeforeMethodsThat().haveNameMatching(".*(doSomethingElse).*");
    }
}
此方法调用检查规则的含义为:优先执行名称匹配“doSomething”或“doAnotherThing”的方法,然后再执行名称匹配“doSomethingElse”的方法。
在编写测试代码时,您可以自定义不同的规则来检查方法调用。如果您的代码违反了规则,就会在测试运行时收到明确的异常消息,这是一种很好的方式来尽早发现并修复代码中的问题。