MVN6️⃣多环境开发 & 跳过测试

1、多环境开发(❗)

  • 项目从开发到上线,会经历多个环境(e.g. 开发、测试、生产)。
  • 不同环境会使用不同的配置(e.g. 数据库)。
  • 👉 需要配置多环境,并且支持环境切换。

1.1、配置多环境

父模块的 pom.xml

profiles:配置多环境。

  • id:唯一标识

  • properties:当前环境可用的 自定义属性

    <profiles>
        <!-- 开发 -->
        <profile>
            <id>dev</id>
            <properties>
                <jdbc.url>jdbc:mysql://localhost:3306/db_dev</jdbc.url>
            </properties>
        </profile>
        <!-- 测试 -->
        <profile>
            <id>test</id>
            <properties>
                <jdbc.url>jdbc:mysql://localhost:3306/db_test</jdbc.url>
            </properties>
        </profile>
        <!-- 生产 -->
        <profile>
            <id>prod</id>
            <properties>
                <jdbc.url>jdbc:mysql://localhost:3306/db_prod</jdbc.url>
            </properties>
        </profile>
    </profiles>
    

编译子模块,查看结果

Hint:移除原来的 properties,仅保留多环境的。

  • 结果jdbc.url 没有被配置文件获取到。
  • 原因:未指定默认环境。

1.2、指定默认环境

2 种方式

  1. 配置文件
  2. 命令行

1.2.1、配置文件

使用 activation 标签,通常指定常用环境。

Hint:若有多个环境都配置了 activation,最后配置的生效。

<profile>
    <id>dev</id>
    <properties>
        <jdbc.url>jdbc:mysql://localhost:3306/db_dev</jdbc.url>
    </properties>
    <!-- 默认 -->
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
</profile>

编译子模块,查看结果

Hint:移除原来的 properties,仅保留多环境的。

结果:配置文件获取到 dev 环境的 jdbc.url

1.2.2、命令行

使用命令行,通常用于临时指定环境。

  1. 进入命令行:两种方式

    • Terminal,切换到 pom.xml 所在目录(CMD)

    • Maven 面板

      image

  2. 执行命令:使用 -P 参数。

    mvn compile -P 环境ID
    
  3. 结果:配置文件获取到 -P 指定环境的 jdbc.url

2、跳过测试(*)

依赖管理 & 生命周期及插件:执行某个插件时,会按顺序先执行执行前面所有插件。

👉 执行 packageinstall 等命令时,必定会先执行 test

  • 测试可以保证代码的正确性。
  • 对于已通过测试的用例,可跳过测试(了解即可)。

2.1、全部跳过

  • Maven 面板:切换 Skip Test 模式

    image

  • Maven 命令行:使用 -D 参数跳过测试。

    mvn 指令 -D skipTests
    # 示例
    mvn compile -D skipTests
    

2.2、部分跳过

配置插件:在父模块的 pom.xml 中

  • skipTests:跳过所有测试(true 跳过,false 不跳过)。
  • includes:跳过测试时,用于指定参与测试的内容(针对 skipTests 为 true)。
  • excludes:不跳过测试时,用于指定不参与测试的内容(针对 skipTests 为 false)。

示例

不跳过测试,但忽略 User 和 Role 模块。

<build>
    <plugins>
        <plugin>
            <!-- 插件 -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            
            <configuration>
                <!-- 不跳过测试 -->
                <skipTests>false</skipTests>
                <excludes>
                    <!-- 忽略 -->
                    <exclude>**/User*.java</exclude>
                    <exclude>**/Role*.java</exclude>	
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>
posted @ 2022-09-05 16:00  Jaywee  阅读(119)  评论(1编辑  收藏  举报

👇