Search code examples
jenkinstestingparametersjenkins-pipeline

How to run a specific test or class using jenkins pipeline


I'm using this command to run my tests:

sh "${mvnHome}/bin/mvn clean test -e -Dgroups=categories.dbd"

but sometimes I want to run a specific test. How can I do it?

I read that I can use "This project is parameterized" but didn't understand how to use it.

I also saw this - https://plugins.jenkins.io/selected-tests-executor/ but it's not good enough since it required an external file.



Solution

  • If you use the maven-surefire-plugin you can simply run

    sh "${mvnHome}/bin/mvn clean test -e -Dgroups=categories.dbd -Dtest=com.example.MyJavaTestClass"
    

    or

    sh "${mvnHome}/bin/mvn clean test -e -Dgroups=categories.dbd -Dtest=com.example.MyJavaTestClass#myTestMethod"
    

    I suggest to add a parameter for the test class/method to your pipeline definition.

    pipeline {
    
      agent any
    
      parameters {
        string defaultValue: '', description: 'Test Name', name: 'TEST_NAME', trim: false
      }
    
      stages {
        stage('run tests') {
          steps {
            script {
              def optionalParameters = ""
              if (params.TEST_NAME != null) {
                optionalParameters += " -Dtest=" + params.TEST_NAME
              }
              sh "${mvnHome}/bin/mvn clean test -e -Dgroups=categories.dbd" + optionalParameters
            }
          }
        }
        ...
      }
      ...
    }