简介:
ArchUnit用于校验类和包是否符合依赖关系规范
添加jar包
<!-- 测试代码结构合理性 --> <dependency> <groupId>com.tngtech.archunit</groupId> <artifactId>archunit-junit5</artifactId> <version>1.0.0-rc1</version> <scope>test</scope> </dependency>
参考代码:
package com.jlpay.agent.merch.entry;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import org.junit.Test;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;
/**
* 测试代码结构是否符合各层依赖关系
* (提交代码前先跑这个测试类,看下依赖是否符合规范)
*
* @author :heyaolei
* @date :2022/8/10
*/
public class StructureTest {
@Test
public void protect_clean_arch() {
JavaClasses classes = new ClassFileImporter()
//不包含测试文件
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
//指定package路径
.importPackages("com.jlpay.agent.merch");
layeredArchitecture()
.consideringAllDependencies()
.layer("adapter").definedBy("com.jlpay.agent.merch.adapter..")
.layer("app").definedBy("com.jlpay.agent.merch.app..")
.layer("domain").definedBy("com.jlpay.agent.merch.domain..")
.layer("client").definedBy("com.jlpay.agent.merch.client..")
.layer("infra").definedBy("com.jlpay.agent.merch.infra..")
.layer("commons").definedBy("com.jlpay.agent.merch.commons..")
// adapter层不应该被任何层依赖
.whereLayer("adapter").mayNotBeAccessedByAnyLayer()
.whereLayer("app").mayNotBeAccessedByAnyLayer()
.whereLayer("client").mayOnlyBeAccessedByLayers("app", "adapter", "domain", "infra", "commons")
// domain 层仅能被app 和 infra层依赖
.whereLayer("domain").mayOnlyBeAccessedByLayers("app", "infra")
.whereLayer("infra").mayOnlyBeAccessedByLayers("commons", "domain")
.whereLayer("commons").mayOnlyAccessLayers("client")
.as("The layer dependencies must be respected")
.because("we must follow the Clean Architecture principle")
.check(classes);
}
}
参考文档:https://blog.csdn.net/cunfen8879/article/details/112544627
标签:domain,jlpay,验证,agent,merch,ArchUnit,com,archunit,体系结构 From: https://www.cnblogs.com/zhougongjin/p/16742437.html