You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins中筛选JUnit测试报告仅发布指定用例结果?

How to Publish Only Specific JUnit Test Results in Jenkins (Without Skipping Tests)

Hey there! Let’s tackle this problem you’ve got: running all your JUnit tests as usual, but only publishing results for those that match your specific naming pattern. I’ve got two reliable approaches to share—pick the one that fits your needs best.

Approach 1: Use the JUnit Plugin’s Built-In Filtering

If your naming pattern is straightforward, the Jenkins JUnit Plugin has a built-in filter that lets you skip publishing non-matching test results without touching test execution. Here’s how to set it up:

  • Open your Jenkins job configuration and scroll to the Publish JUnit test result report step.
  • In the Test report XMLs field, keep your standard path (like **/TEST-*.xml)—this tells Jenkins where to find all test results.
  • Click the Advanced button to expand more options.
  • Look for the Include test names matching regular expression field. Enter your regex pattern here. For example:
    • If you want tests starting with Feature_, use ^Feature_.*
    • If you want tests containing API_ in the name, use .*API_.*
  • Save your job configuration and run it. All tests will execute, but only the ones matching your regex will show up in the published report.

This is the quickest method if your filtering needs are simple—no extra scripts required!

Approach 2: Preprocess JUnit XML Files (For Advanced Filtering)

If you need more control (like filtering based on test class names, packages, or complex naming rules), you can preprocess the JUnit XML files before publishing. This involves writing a quick script to strip out non-matching test cases from the XMLs.

Example with Python Script

Add an "Execute shell" (or "Execute Windows batch command") step right after your test run and before the JUnit report publish step. Use a script like this:

import xml.etree.ElementTree as ET
import os
import re

# Define your test name pattern (adjust this to match your needs)
test_name_pattern = re.compile(r'^Feature_.*')

# Path to your JUnit test reports (update this to your actual directory)
report_directory = './target/surefire-reports'

# Loop through all JUnit XML files
for root, _, files in os.walk(report_directory):
    for file in files:
        if file.startswith('TEST-') and file.endswith('.xml'):
            file_path = os.path.join(root, file)
            tree = ET.parse(file_path)
            test_suite = tree.getroot()

            # Collect all test cases that don't match the pattern
            non_matching_tests = []
            for testcase in test_suite.findall('testcase'):
                test_name = testcase.get('name')
                if not test_name_pattern.match(test_name):
                    non_matching_tests.append(testcase)

            # Remove non-matching tests from the XML
            for test in non_matching_tests:
                test_suite.remove(test)

            # Save the modified XML file
            tree.write(file_path)

Example with Jenkins Pipeline (Groovy)

If you’re using a Jenkinsfile, you can integrate the filtering directly into your pipeline:

pipeline {
    agent any
    stages {
        stage('Run All Tests') {
            steps {
                // Execute your test command here (e.g., Maven, Gradle)
                sh 'mvn test'
            }
        }
        stage('Filter Test Results') {
            steps {
                script {
                    def reportDir = './target/surefire-reports'
                    def namePattern = ~/^Feature_.*/ // Adjust your pattern here

                    // Process each JUnit XML file
                    new File(reportDir).eachFileMatch(~/TEST-.*\.xml/) { xmlFile ->
                        def xmlParser = new XmlParser()
                        def testSuite = xmlParser.parse(xmlFile)

                        // Remove non-matching test cases
                        testSuite.testcase.findAll { tc ->
                            !namePattern.matcher(tc.@name).matches()
                        }.each { tc ->
                            tc.parent().remove(tc)
                        }

                        // Save the modified XML
                        def printer = new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile)))
                        printer.print(testSuite)
                    }
                }
            }
        }
        stage('Publish Filtered Report') {
            steps {
                junit '**/TEST-*.xml'
            }
        }
    }
}

Key Notes

  • Both approaches ensure all tests run—we’re only hiding the non-matching results from the published report.
  • The built-in filter is great for simple regex patterns, while the script approach gives you full control for complex rules.
  • Always test your regex pattern first to make sure it matches exactly the tests you want to keep!

内容的提问来源于stack exchange,提问作者Pritish Panda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:30:41