Home > Back-end >  How to run maven tests in gitlab ci without rebuilding the project?
How to run maven tests in gitlab ci without rebuilding the project?

Time:07-02

I created a Maven Spring boot project. In the build job I want to only build the project without tests. In the test stage I want to run unit tests and use the build from the build stage, so no new build in test stage. The problem is that mvn runs a build again in the test stage.

image: maven:3.8-jdk-11

stages:          
  - build
  - test

build-job:       
  stage: build
  script:
    - mvn compile
  artifacts:
    paths:
      - target

test-job:
  stage: test
  script:
    - mvn test


If it runs a build in the test stage again, then the build stage wouldnt be necessary. But I want separate stages for both to better separate and see where something goes wrong.

CodePudding user response:

At first, in my opinion the idea to split build process into different stages might look attractive but actually does not have any practical benefits, especially in your case when you are trying to split packaging into compile, test and, probably, package stages. Think about following:

  • in case of pull request pipeline what we actually need to get is:
    • the answer whether the changes from pull request do actually work, i.e. yes or no
    • reports from other tools (code coverage, static code analysis, etc)
    • build logs to analyse failures
  • in case of release pipeline we also expect to get artifacts deployed into DML

Everything mentioned above is already covered by maven - there is no practical reason to split mvn package into separate parts, moreover everything in maven project till verify phase is about the code only - CI should not intervene in mvn package.

Now, why do we need stages in CI? Obviously we need stages when our CI process somehow depends on environment, i.e. when we are performing build against different platforms or we would like to run external tools, however there is no place for external tools till verify phase.

At second, if you really want to split mvn package into separate stages the options are following:

  • configure maven plugins to skip execution relying on maven/system properties, most of maven plugins have such capability, e.g. to skip compile you may pass -Dmaven.main.skip=true to command line or setup something like <skipMain>my.cool.property</skipMain> and pass -Dmy.cool.property=true
  • as previous one, but consolidate properties in maven profiles
  • reconstruct maven lifecycle phase manually, for example in you case it might look something like: mvn resources:testResources compiler:testCompile surefire:test

However, all of those options look very poor from my perspective due to following considerations:

  • it is very complex and ugly
  • it requires to keep in sync CI definition and maven poms
  • Related