跳到正文
cccskills
免费在 GitHub 公开中文介绍

testing-internals

本指南沿着 `bt.cmd`、`tests.cmd` 经 Bazel 和 JUnit 执行测试的路径,排查测试未发现或选错、构建失败、内存问题及调试器配置。

原文查看原文说明

Debug IntelliJ `bt.cmd` and `tests.cmd` runs, discovery, and runner internals.

JetBrains/intellij-community星标 20,684(GitHub 20,684 + cccskills 0)

实测评分 未实测

查看安装方法

适用场景

  • 查找测试类未被发现的原因
  • 确认筛选条件会运行哪些测试
  • 排查测试启动时的构建或内存问题

中文介绍

功能

本指南沿着 IntelliJ 的 bt.cmd 和 tests.cmd 执行路径,追踪测试如何经过 Bazel 和 JUnit,并据此排查运行问题。测试未被发现时,可以检查类名匹配模式和类路径;运行了意外的测试时,可以检查测试组设置和并行分桶。指南还说明构建失败时如何检查依赖关系及 BUILD.bazel 同步,内存不足时如何调整 JVM 设置,以及用于连接调试器的属性。

适用场景

当测试类明明存在却没有运行、实际运行的测试与指定内容不符,或测试开始前 Bazel 就报错时,可以使用本指南。它帮助您从运行脚本、测试发现到 JVM 启动,逐步判断应检查哪个环节。

使用示例

  • “请查找 tests.cmd 没有发现我的测试的原因。”
  • “请确认这个测试匹配模式会选中哪些类。”
  • “请说明如何配置测试调试运行。”

注意事项

本指南以 IntelliJ 仓库的测试执行方式为前提。命令示例和配置属性对应文中介绍的 bt.cmd、tests.cmd、Bazel 和 JUnit 执行路径。

本介绍由 AI(OpenAI Codex)根据公开的 SKILL.md 撰写。准确的规格请查看下方原文。

文档检查

AI 根据 SKILL.md 的内容检查了需要注意的操作和使用前提。评分只依据实际运行的结果(实测对比)。

安全性发送数据、删除文件、执行命令等是否有说明
A良好内容主要是检查配置,并明确指出不要运行 `bazel clean`。
安装难易度所需工具和 API 密钥是否少且有说明
B部分不足需要 IntelliJ 的 Bazel 和 JUnit 环境,但未提供安装步骤。

不计入评分。 由 AI(OpenAI Codex)于 2026年10月28日 评估。仅供参考,安装前请同时查看原文。

如果您认为评估有误,请申请复核

请写明哪一项有误以及原因。无需登录。我们会对照 SKILL.md 重新评估,并在此处更新结果。

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

包含的文件(1)

  • SKILL.md25.7 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

<!-- Generated by community/.ai/render-guides.mjs; edit community/.agents/skills/testing-internals/SKILL.md -->

Test Execution Internals

This document explains tests.cmd internals and helps troubleshoot test execution issues.

Overview

The test execution chains:

bt.cmd → bazel test <jps_test label> → JUnit5BazelRunner
tests.cmd → Bazel → IdeaUltimateRunTestsBuildTarget → TestingTasksImpl → JUnit 5

A module of the migrated list or of a bt.json area runs through bt. Every other module runs through tests.cmd.

Key components:

  • tests.cmd: Shell script that invokes Bazel with test parameters
  • Bazel target: //build:local_idea_ultimate_run_tests_build_target
  • TestingOptions: Parses -Dintellij.build.test.* system properties
  • TestingTasksImpl: Orchestrates classpath assembly and JVM setup
  • JUnit runners: Execute tests in a forked JVM process

Common Issues & Solutions

Tests Not Found

Symptoms:

  • "No tests found" message
  • Test class exists but isn't executed

Causes & Solutions:

  1. Pattern mismatch - Simple class names don't work (see Pattern Matching below):

    # WRONG - simple name won't match FQN
    -Dintellij.build.test.patterns=MyTest
    
    # CORRECT - use wildcard or FQN
    -Dintellij.build.test.patterns=*MyTest
    -Dintellij.build.test.patterns=com.example.MyTest
    
  2. Test not in classpath - The test class must be in a module that's part of the test classpath. Check if the module is included in the build.

  3. Test class not recognized - Ensure class has JUnit annotations.

OutOfMemoryError

Solution: Increase heap size:

./tests.cmd \
  --module <module> \
  --test MyTest \
  -Dintellij.build.test.jvm.memory.options=-Xmx8g

Bazel Build Fails

Symptoms:

  • Build errors before tests run
  • Missing dependencies

Solutions:

  1. Check module dependencies - Ensure test module has required dependencies in .iml file.

  2. Verify BUILD.bazel is synced - Run ./build/jpsModelToBazel.cmd after changing .iml files.

Note: Bazel incremental builds are always correct. Do not use bazel clean - it won't help.

Test Discovery Issues

Symptoms:

  • Wrong tests executed
  • Tests filtered unexpectedly

Debug steps:

  1. Check test groups - If using groups, verify testGroups.properties configuration.

  2. Check bucketing - For parallel execution, tests are distributed by hash:

    # See which bucket a test falls into
    -Didea.test.runners.count=4
    -Didea.test.runner.index=0  # Run only bucket 0
    
  3. Check class filters - TestCaseLoader applies pattern matching before test execution.

Debug Mode

Enable debug mode to attach a debugger:

./tests.cmd \
  --module <module> \
  --test MyTest \
  -Dintellij.build.test.debug.enabled=true \
  -Dintellij.build.test.debug.port=5005 \
  -Dintellij.build.test.debug.suspend=true

Then attach debugger to port 5005.

Quick Reference

PropertyPurpose
intellij.build.test.patternsTest class patterns (semicolon-separated)
intellij.build.test.groupsTest groups to run
intellij.build.test.attempt.countRetry count for flaky tests
intellij.build.test.jvm.memory.optionsJVM memory settings
intellij.build.test.debug.enabledEnable remote debugging

Detailed Reference

Execution Flow Diagram

┌─────────────────────────────────────────────────────────────────────────────┐
│  1. COMMAND LINE                                                            │
│     ./tests.cmd --module <module> --test MyTest                             │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  2. SHELL SCRIPT                                                            │
│     tests.cmd → community/build/run_build_target.sh                         │
│     Maps --module/--test to -D properties, wraps as --jvm_flag=<arg>        │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  3. BAZEL                                                                   │
│     bazel run //build:local_idea_ultimate_run_tests_build_target            │
│     (defined in build/BUILD.bazel)                                          │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  4. BUILD TARGET ENTRY POINT                                                │
│     IdeaUltimateRunTestsBuildTarget.main()                                  │
│     → UltimateProjectTestingTasks.runTests()                                │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  5. TEST OPTIONS PARSING                                                    │
│     UltimateProjectTestingOptions (extends TestingOptions)                  │
│     Reads all -Dintellij.build.test.* system properties                     │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  6. TEST EXECUTION ORCHESTRATION                                            │
│     TestingTasksImpl.runTests()                                             │
│     - Builds test classpath                                                 │
│     - Prepares JVM arguments and system properties                          │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  7. FORKED TEST PROCESS                                                     │
│     TestingTasksImpl.runJUnit5Engine()                                      │
│     Spawns new JVM with bootstrap classpath                                 │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                    ┌───────────────┴───────────────┐
                    ▼                               ▼
┌───────────────────────────────────┐ ┌───────────────────────────────────────┐
│  8a. JUNIT 5 TESTS                │ │  8b. JUNIT 3/4 TESTS (Legacy)         │
│  JUnit5TeamCityRunner.main()      │ │  JUnit5TeamCityRunner.main()          │
│  - Uses JUnit Platform Launcher   │ │  - Uses JUnit Platform Launcher       │
│  - ClassNameFilter                │ │  - ClassNameFilter                    │
│  - PostDiscoveryFilter            │ │  - PostDiscoveryFilter                │
└───────────────────────────────────┘ └───────────────────────────────────────┘
                    │                               │
                    └───────────────┬───────────────┘
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  9. TEST DISCOVERY & FILTERING                                              │
│     TestCaseLoader                                                          │
│     - Loads test classes from classpath roots                               │
│     - Applies pattern/group filters                                         │
│     - Handles bucketing for parallel execution                              │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  10. TEST EXECUTION                                                         │
│      JUnit Platform executes tests                                          │
│      TCExecutionListener reports results to TeamCity                        │
└─────────────────────────────────────────────────────────────────────────────┘

Key Classes Reference

Entry Points & Orchestration

ClassPurpose
IdeaUltimateRunTestsBuildTargetUltimate tests entry point, calls UltimateProjectTestingTasks
CommunityRunTestsBuildTargetCommunity tests entry point, calls TestingTasks
UltimateProjectTestingTasksUltimate-specific test orchestration (YourKit, network restrictions)
TestingTasksInterface for test execution
TestingTasksImplCore test execution logic

Test Options

ClassPurpose
TestingOptionsBase class for all test options. Parses -Dintellij.build.test.* properties
UltimateProjectTestingOptionsUltimate-specific options (YourKit, skip community tests)

JUnit 5 Test Runners

ClassPurpose
JUnit5TeamCityRunnerRuns JUnit 3/4 tests using the JUnit Vintage test engine, or JUnit5 tests using the JUnit Jupiter test engine
TCExecutionListenerReports test results to TeamCity via service messages

Test Discovery & Loading

ClassPurpose
TestCaseLoaderDiscovers and filters test classes
TestAllJUnit 3 test suite, collects all tests
TestClassesFilterPattern/group-based test filtering

Bucketing & Distribution

ClassPurpose
BucketingSchemeInterface for test distribution
HashingBucketingSchemeDefault: hash-based distribution
TestsDurationBucketingSchemeDuration-aware distribution

Test Module Hierarchy

Entry Points by Product

ProductEntry PointDefault mainModuleSource
IDEA UltimateIdeaUltimateRunTestsBuildTargetintellij.idea.ultimate.tests.mainbuild/src/
CommunityCommunityRunTestsBuildTargetintellij.idea.community.main.testscommunity/build/src/
RustRoverRustRoverRunTestsBuildTargetintellij.idea.ultimate.tests.mainrustrover/build/src/
RubyMineRubyRunTestsBuildTargetintellij.idea.ultimate.tests.mainruby/build/src/
CLionCLionRunTestsBuildTargetintellij.idea.ultimate.tests.mainCIDR/clion-build/src/

Note: Product entry points (RustRover, RubyMine, CLion) inherit intellij.idea.ultimate.tests.main as the default, but to run product-specific tests, use the dedicated test module via --module. See TESTING.md for the correct module per product.

CI-Defined Test Modules

From intellij-teamcity-config/.teamcity/src/ijplatform/KnownModules.kt:

CI ConstantModule Name
ULTIMATE_TESTSintellij.idea.ultimate.tests.main
COMMUNITY_MAINintellij.idea.community.main.tests
GOLAND_TESTSintellij.goland.tests
PYTHON_TESTSintellij.python.tests
PHPSTORM_MAINintellij.phpstorm.main.tests
CLION_MAINintellij.clion.main.tests
RUSTROVER_MAINintellij.rustrover.main.tests
KOTLIN_TESTSintellij.kotlin.tests
KOTLIN_ULTIMATE_ALL_TESTSintellij.kotlin-ultimate.all-tests
DATABASE_TESTSintellij.database.tests
DATABASE_SQL_TESTSintellij.database.sql.tests

Module Configuration

Default mainModule is set in:

  • UltimateProjectTestingOptions.kt:36 - Ultimate: intellij.idea.ultimate.tests.main
  • CommunityRunTestsBuildTarget.kt:28 - Community: intellij.idea.community.main.tests

Ultimate Test Module Tree (Simplified)

intellij.idea.ultimate.tests.main
├── intellij.idea.ultimate.tests
├── intellij.idea.ultimate.tests.kotlin
├── intellij.platform.tests
├── intellij.java.tests
└── ... (hundreds of test modules)

Separate hierarchies (NOT in .main):
├── intellij.idea.ultimate.tests.kotlin.k2
│   └── intellij.devkit.kotlin.fir.tests
├── intellij.idea.ultimate.tests.devBuildTests
└── intellij.kotlin.tests

TestingOptions Properties

TestingOptions Properties

Most options use the intellij.build.test.* prefix. Bucketing uses idea.test.* prefix.

// Test selection (mutually exclusive, in priority order)
testConfigurations  // -Dintellij.build.test.configurations=<config>
testPatterns        // -Dintellij.build.test.patterns=<pattern>
testGroups          // -Dintellij.build.test.groups=<group>

// Test execution
mainModule          // -Dintellij.build.test.main.module=<module>
attemptCount        // -Dintellij.build.test.attempt.count=<n>

// JVM configuration
jvmMemoryOptions    // -Dintellij.build.test.jvm.memory.options=<opts>
customRuntimePath   // -Dintellij.build.test.jre=<path>

// Debugging
isDebugEnabled      // -Dintellij.build.test.debug.enabled=<bool>
debugPort           // -Dintellij.build.test.debug.port=<port>
isSuspendDebugProcess // -Dintellij.build.test.debug.suspend=<bool>

// Bucketing (parallel execution) - NOTE: uses idea.test.* prefix
bucketsCount        // -Didea.test.runners.count=<n>
bucketIndex         // -Didea.test.runner.index=<n>

// Coverage
enableCoverage      // -Dintellij.build.test.coverage.enabled=<bool>
coveredClassesPatterns // -Dintellij.build.test.coverage.include.class.patterns=<patterns>

Bazel Target Configuration

The test target is defined in build/BUILD.bazel:

java_binary(
  name = "local_idea_ultimate_run_tests_build_target",
  runtime_deps = [":build"],
  main_class = "IdeaUltimateRunTestsBuildTarget",
  data = ALL_ULTIMATE_TARGETS + [BAZEL_TARGETS_JSON_ULTIMATE],
  jvm_flags = [
    "-Dintellij.build.console.exporter.to.temp.file=true",
    "-Dintellij.build.console.messages.verbose=false",
    "-Dintellij.build.clean.output.root=false",      # Reuse compiled classes
    "-Dintellij.build.use.compiled.classes=true",    # Skip recompilation
    "-Dintellij.build.bazel.targets.json.file=$(rlocationpath %s)" % BAZEL_TARGETS_JSON_ULTIMATE,
  ],
  add_opens = INTELLIJ_ADD_OPENS,
)

Test Process JVM Configuration

TestingTasksImpl.prepareEnvForTestRun() configures the forked test JVM:

// Key system properties set for test process:
"idea.home.path"     → projectHome
"idea.config.path"   → tempDir/config
"idea.system.path"   → tempDir/system
"java.io.tmpdir"     → tempDir

// JVM options:
"-XX:+HeapDumpOnOutOfMemoryError"
"-XX:HeapDumpPath=<snapshotsDir>/intellij-tests-oom-<timestamp>.hprof"
"-Xms750m -Xmx1024m"  // or custom from jvmMemoryOptions
// Plus --add-opens for module access

Passing JVM Args to Test Process

There are two mechanisms for passing JVM arguments to the test JVM process:

1. Memory Options (intellij.build.test.jvm.memory.options)

For JVM memory settings like heap size, use the dedicated property:

./tests.cmd --module <module> --test <pattern> -Dintellij.build.test.jvm.memory.options="-Xmx4g -Xms2g"

Multiple options are space-separated within quotes. These options are added to the beginning of the JVM arguments via VmOptionsGenerator.generate().

Implementation (see TestingTasksImpl.kt, runJUnit5Engine method):

val customMemoryOptions = options.jvmMemoryOptions?.trim()?.split(Regex("\\s+"))?.takeIf { it.isNotEmpty() }
jvmArgs.addAll(
  index = 0,
  elements = VmOptionsGenerator.generate(
    customVmMemoryOptions = if (customMemoryOptions == null) mapOf("-Xms" to "750m", "-Xmx" to "1024m") else emptyMap(),
    additionalVmOptions = customMemoryOptions ?: emptyList(),
    // ... other parameters omitted
  ),
)

2. Pass-through System Properties (pass.* prefix)

To pass arbitrary system properties to the test JVM, use the pass. prefix. The prefix is stripped before passing to the test process:

./tests.cmd --module <module> --test <pattern> -Dpass.my.custom.property=value -Dpass.some.flag=true

Results in test JVM receiving:

  • -Dmy.custom.property=value
  • -Dsome.flag=true

Implementation (see TestingTasksImpl.kt, prepareEnvForTestRun method):

for ((key, value) in System.getProperties()) {
  key as String
  if (key.startsWith("pass.")) {
    systemProperties.put(key.substring("pass.".length), value as String)
  }
}

This is a TeamCity convention for passing properties to nested processes.

Combined Example

./tests.cmd \
  --module <module> \
  --test MyTest \
  -Dintellij.build.test.jvm.memory.options="-Xmx4g" \
  -Dpass.my.test.flag=enabled \
  -Dpass.debug.level=verbose

Important: Properties without pass. prefix are consumed by the build scripts, NOT passed to the test JVM.

Test Discovery Flow

Step-by-Step Pattern Matching

┌─────────────────────────────────────────────────────────────────────────────┐
│  PATTERN INPUT                                                              │
│  -Dintellij.build.test.patterns=*MyTest                                     │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  PATTERN COMPILATION (TestClassesFilter.compilePattern)                     │
│  filter.replace("$","\\$").replace(".","\\.");replace("*",".*")             │
│  "*MyTest" → ".*MyTest"                                                     │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  CLASS DISCOVERY (ClassFinder)                                              │
│  Scans JARs for *Test.class files, extracts FQN:                            │
│  org/example/MyTest.class → "org.example.MyTest"                            │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  PATTERN MATCHING (PatternListTestClassFilter.matches)                      │
│  pattern.matcher(className).matches()  ← FULL STRING MATCH                  │
│  ".*MyTest".matches("org.example.MyTest") → true                            │
└─────────────────────────────────────────────────────────────────────────────┘

Pattern Transformation Table

Input PatternCompiled RegexMatches org.example.MyTest?
MyTestMyTest❌ NO (not full match)
*MyTest.*MyTest✅ YES
org.example.MyTestorg\.example\.MyTest✅ YES
org.example.*org\.example\..*✅ YES
*.*✅ YES (matches all)

Key Implementation Details

  1. Pattern Compilation (TestClassesFilter.compilePattern()):

    filter = filter.replace("$", "\\$").replace(".", "\\.").replace("*", ".*");
    return Pattern.compile(filter);
    
  2. Pattern Matching (PatternListTestClassFilter.matches()):

    return ContainerUtil.exists(patterns, pattern -> pattern.matcher(className).matches());
    
    • Uses matches() NOT find() - requires ENTIRE string to match
    • className is ALWAYS the fully qualified name (FQN)
  3. ClassNameFilter (JUnit 5) - Fast pre-filter on class names

    • Calls TestCaseLoader.isClassNameIncluded(className)
    • Applied to EVERY class in classpath (must be fast)
  4. PostDiscoveryFilter (JUnit 5) - Post-discovery filter

    • Calls TestCaseLoader.isClassIncluded(className)
    • Checks bucketing (which runner should execute this test)
  5. TestCaseLoader.fillTestCases() (JUnit 3/4) - Scans classpath roots

    • Uses ClassFinder to find all *Test.class files
    • Calls isPotentiallyTestCase() which calls filter's matches()
    • Applies group-based filtering from testGroups.properties

Why Simple Class Names NEVER Work

Root Cause: Pattern.matches() requires the ENTIRE string to match.

// Pattern: "MyTest" → Regex: "MyTest"
// className: "org.example.MyTest"
"MyTest".matches("org.example.MyTest")  // Returns FALSE

// Pattern: "*MyTest" → Regex: ".*MyTest"
".*MyTest".matches("org.example.MyTest")  // Returns TRUE

This applies to ALL modules (default and non-default). Always use:

  • FQN: org.example.MyTest
  • Or wildcard: *MyTest

Related Documentation

  • TESTING.md - How to run tests via tests.cmd (quick start, parameters, examples)
  • Writing Tests - How to write tests (framework, @TestApplication, fixtures, EDT)

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

actions

免费有简介

实现或修改 IntelliJ `AnAction`,并在 `plugin.xml` 中注册。将显示名称和说明写入消息资源文件,按需设置图标,并通过事件协程作用域启动挂起任务,避免同步处理阻塞 IDE。

  • 为 IDE 菜单添加操作
  • 修改操作注册或图标
  • 整理操作名称和说明
JetBrains/intellij-community2.1万2026年10月29日 更新

bazel-test-migration

免费有简介

将 IntelliJ JPS 测试模块迁移到 Bazel,并排查仅在 Bazel 中出现的失败。根据症状检查依赖、插件、测试数据和 runfiles,重新生成并验证目标。

  • 将 JPS 测试模块迁移到 Bazel
  • 排查仅在 Bazel 中失败的测试
  • 检查测试依赖和数据配置
JetBrains/intellij-community2.1万2026年10月29日 更新

code-style

免费有简介

按 IntelliJ 项目规范编写或审查 Kotlin 和 Java 代码,涵盖语言选择、格式、密封类型、线程注解及控制流异常处理。

  • 按 IntelliJ 规范编写 Kotlin
  • 审查 Java 代码
  • 检查异常处理和密封类型分支
JetBrains/intellij-community2.1万2026年10月29日 更新

commits

免费有简介

本指南帮助您按 IntelliJ 项目规则拆分更改并撰写提交信息:有工单时使用编号和变更说明,无工单时使用标签与子系统名,并在需要时说明原因和决定。

  • 按项目格式编写带工单号的提交信息
  • 整理测试或文档提交并选择合适标签
  • 按规则修改已有提交信息
JetBrains/intellij-community2.1万2026年10月29日 更新

使用多个 Python 类型检查器比较代码片段或文件的类型推断和报错判断,并汇总各工具的结论、耗时与诊断信息,可保存为 Markdown 报告。

  • 比较不同检查器的类型推断
  • 确认代码是否会被判为类型错误
  • 查看多个工具的诊断差异
JetBrains/intellij-community2.1万2026年10月29日 更新

整理 Compose Desktop 界面中的状态和副作用,让可组合函数负责绘制,由展示器或协调器处理应用决策。了解状态归属、Effect、可复用组件接口、延迟列表键、动画和性能,适用于单项界面修改。

  • 分离界面绘制与展示器决策
  • 整理界面状态的归属
  • 检查 Effect 键和协程用法
JetBrains/intellij-community2.1万2026年10月29日 更新

查看 JetBrains 的全部技能

报告此技能的问题