К основному содержанию
скилл CX Codex

platform-apex-test-run — скилл для Claude Code: как установить

Запускает тесты Apex через Salesforce CLI, анализирует покрытие кода и ведёт цикл исправления упавших тестов. Помогает разобрать ошибки перед деплоем.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add forcedotcom/sf-skills --skill platform-apex-test-run -a claude-code
Открыть на GitHub

Что делает platform-apex-test-run

Скилл выполняет тесты Apex через sf apex run test и собирает метрики покрытия строк. Он изолирует прогоны с правилом SeeAllData=false. Для проверки триггеров запускаются тесты на пачках от 251 записи, чтобы перейти границу пакета в 200 записей.

Для запуска требуются системные утилиты sf версии от 2.0.0, python3 от 3.10.0 и jq от 1.6.0. Скилл сначала прогоняет узкий набор тестов ради быстрой локализации сбоя. Для написания самого продакшен-кода он не подходит: эту работу автор рекомендует передавать в platform-apex-generate.

Какие задачи решает

  • Запустить модульные тесты Apex в целевой организации через sf
  • Найти непокрытые строки кода и пробелы в сценариях
  • Разобрать стек-трейсы и причины падения тестовых методов
  • Проверить обработку пачек из 251+ записей для триггеров

Примеры запросов агенту

  • Запусти тесты для класса OrderTriggerHandlerTest в орге dev-org и покажи покрытие
  • Разбери, почему падает метод testBulkInsert в AccountServiceTest
  • Проверь покрытие кода для классов биллинга и найди неохваченные строки

Как установить platform-apex-test-run

1Через Skills CLI (Vercel)

npx skills add forcedotcom/sf-skills --skill platform-apex-test-run -a claude-code

2Вручную: положить файлы

~/.claude/skills/platform-apex-test-run/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/platform-apex-test-run/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора167

platform-apex-generate Пишет и рефакторит Apex-классы и триггеры, затем прогоняет код через анализатор и тесты. Пригодится, когда в проекте много Salesforce-кода. CX Codex +1 7 100установок platform-apex-test-generate Скилл пишет и чинит тест-классы Apex: фабрики данных, массовые прогоны, моки и разбор покрытия. Пригодится, когда перед деплоем не хватает покрытия. CX Codex +1 7 000установок platform-soql-query Пишет и оптимизирует запросы SOQL/SOSL в Salesforce: от формулировки на естественном языке до анализа селективности и плана запроса. CX Codex +1 6 800установок platform-apex-logs-debug Скилл разбирает debug-логи Salesforce: находит причину падения, ловит превышение governor limits и объясняет стек вызовов. CX Codex +1 6 800установок platform-metadata-deploy Оркестрирует деплой метаданных Salesforce через sf CLI v2, проверяет изменения перед релизом и ведёт развёртывание в прод без прямых запусков deploy start. CX Codex +1 6 700установок platform-metadata-retrieve Скилл тянет метаданные из org в локальный проект через sf project retrieve start: все изменения, каталог, тип, манифест или пакет. CX Codex +1 6 600установок platform-permission-set-generate Создаёт метаданные Salesforce PermissionSet XML для прав объектов, полей, пользователей и приложений. Нужен при настройке FLS, вкладок и развёртывании наборов разрешений. CX Codex +1 6 500установок platform-docs-get Тянет официальную документацию Salesforce и заставляет агента отвечать по ней, а не по чужим блогам. Полезен, когда страницы рендерятся через JS и обычный fetch возвращает пустую оболочку. CX Codex +1 6 500установок

Похожие

salesforce-apex-quality официальный github Проверяет Apex-код на риски governor limits, проблемы безопасности и пробелы в тестах. Подходит для ревью классов, триггеров и тестовых классов. 884установок salesforce-apex-cursorrules-prompt-file PatrickJS Правило для Cursor, которое настраивает ИИ на разработку Salesforce на Apex: очередь вместо @future, паттерны GoF и минимум комментариев. ★ 41 011звёзд репо apex официальный github Правило задаёт Copilot стиль кода Apex: массовые операции, имена классов и методов, проверка прав доступа. Пригодится, если вы пишете триггеры и классы на платформе Salesforce. ★ 40 418звёзд репо salesforce-development Mindrally Скилл задаёт агенту правила разработки на Salesforce: Apex, триггеры, Lightning Web Components, SOQL и метаданные. Пригодится, когда пишете код для org и хотите, чтобы агент держал стиль и лимиты платформы. CX Codex +1 659установок salesforce-developer https://github.com/Jeffallan Пишет Apex-классы, собирает Lightning Web Components, оптимизирует SOQL-запросы и настраивает пакетную обработку на платформе Salesforce. Следит за governor limits и булкифицирует код. CX Codex +1 4 300установок salesforce-dx Mindrally Скилл задаёт агенту правила разработки на Salesforce DX: Apex, триггеры, LWC, scratch orgs и выкладка через SFDX CLI. CX Codex +1 688установок

Рядом в теме «Тесты и QA»

Всё по теме «Тесты и QA» →

Вопросы о platform-apex-test-run

Как установить platform-apex-test-run в Claude Code?

Для установки выполните команду npx skills add forcedotcom/sf-skills --skill platform-apex-test-run -a claude-code.

Что делает platform-apex-test-run?

Он запускает тесты Apex через sf apex run test, находит непокрытые строки и помогает устранять сбои в тестовых классах.

Какие CLI-инструменты нужны для работы?

Требуются установленные sf от версии 2.0.0, python3 от 3.10.0 и jq от 1.6.0.

Исходный текст

SKILL.md · Apache-2.0
---
name: platform-apex-test-run
description: "Apex test execution, coverage analysis, and test-fix loops with 120-point scoring. Use when the user runs Apex tests, checks code coverage, fixes failing tests, or touches *Test.cls / *_Test.cls files. DO NOT TRIGGER when writing Apex production code (use platform-apex-generate), Agentforce agent testing (use agentforce-test), or Jest/LWC tests (use experience-lwc-generate)."
metadata:
  version: "1.2"
  domains: ["Platform"]
  relatedSkills:
    - "agentforce-test"
    - "experience-lwc-generate"
    - "platform-apex-generate"
    - "platform-apex-logs-debug"
    - "platform-data-manage"
    - "platform-metadata-deploy"
  cliTools:
    - tool: ["jq"]
      semver: ">=1.6.0"
    - tool: ["python3"]
      semver: ">=3.10.0"
    - tool: ["sf"]
      semver: ">=2.0.0"
---

# platform-apex-test-run: Salesforce Test Execution & Coverage Analysis

Use this skill when the user needs **Apex test execution and failure analysis**: running tests, checking coverage, interpreting failures, improving coverage, and managing a disciplined test-fix loop for Salesforce code.

## When This Skill Owns the Task

Use `platform-apex-test-run` when the work involves:
- `sf apex run test` workflows
- Apex unit-test failures
- code coverage analysis
- identifying uncovered lines and missing test scenarios
- structured test-fix loops for Apex code

Delegate elsewhere when the user is:
- writing or refactoring production Apex → `platform-apex-generate` skill
- testing Agentforce agents → `agentforce-test` skill
- testing LWC with Jest → [experience-lwc-generate](../experience-lwc-generate/SKILL.md)

---

## Required Context to Gather First

Ask for or infer:
- target org alias
- desired test scope: single class, specific methods, suite, or local tests
- coverage threshold expectation
- whether the user wants diagnosis only or a test-fix loop
- whether related test data factories already exist

---

## Recommended Workflow

### 1. Discover test scope
Identify:
- existing test classes
- target production classes
- test data factories / setup helpers

### 2. Run the smallest useful test set first
Start narrow when debugging a failure; widen only after the fix is stable.

### 3. Analyze results
Focus on:
- failing methods
- exception types and stack traces
- uncovered lines / weak coverage areas
- whether failures indicate bad test data, brittle assertions, or broken production logic

### 4. Run a disciplined fix loop
When the issue is code or test quality:
- delegate code fixes to `platform-apex-generate` skill when needed
- add or improve tests
- rerun focused tests before broader regression

### 5. Improve coverage intentionally
Cover:
- positive path
- negative / exception path
- bulk path (251+ records where appropriate)
- callout or async path when relevant

---

## High-Signal Rules

| Rule | Rationale |
|------|-----------|
| Default to `SeeAllData=false` | Ensures test isolation; prevents reliance on org-specific data |
| Every test must assert meaningful outcomes | Tests with no assertions prove nothing and give false confidence |
| Test bulk behavior with 251+ records | Triggers process in batches of 200; 251 records crosses the boundary |
| Use factories / `@TestSetup` when they improve clarity | Consistent data creation in one place; rolled back between test methods |
| Pair `Test.startTest()` with `Test.stopTest()` for async | Ensures async operations (queueable, future) complete before assertions |
| Do not hide flaky org dependencies inside tests | Prevents intermittent failures tied to org state |

---

## Gotchas

| Issue | Resolution |
|-------|------------|
| Test passes locally but fails in CI org | Check for `SeeAllData=true` or undeclared dependencies on org-specific records |
| Coverage drops unexpectedly after refactor | Run focused class-level tests first, then widen to `RunLocalTests` to confirm |
| "Uncommitted work pending" error in callout test | DML and HTTP callouts cannot be mixed in the same test context without `Test.startTest()` wrapping |
| Mock not taking effect in test | Ensure `Test.setMock()` is called before the code that makes the callout |
| `@TestSetup` data missing in test method | `@TestSetup` data is committed per test method — re-query it; do not store in static variables |
|  API version 67.0 and higher without necessary access level checks | Check failing SOQL/DML stack traces for CRUD/FLS access errors, using System.runAs with an assigned permission set when user-mode behavior is intended, or documenting a justified `SYSTEM_MODE` path when system access is required |

---

## Output Format

When finishing, report in this order:
1. **What tests were run**
2. **Pass/fail summary**
3. **Coverage result**
4. **Root-cause findings**
5. **Fix or next-run recommendation**

Suggested shape:

```text
Test run: <scope>
Org: <alias>
Result: <passed / partial / failed>
Coverage: <percent / key classes>
Issues: <highest-signal failures>
Next step: <fix class, add test, rerun scope, or widen regression>
```

---

## Cross-Skill Integration

| Need | Delegate to | Reason |
|------|-------------|--------|
| Fix production code or author test classes | `platform-apex-generate` skill | Code generation and repair |
| Create bulk / edge-case test data | [platform-data-manage](../platform-data-manage/SKILL.md) | Realistic test datasets |
| Deploy updated tests to org | [platform-metadata-deploy](../platform-metadata-deploy/SKILL.md) | Deployment workflows |
| Inspect detailed runtime logs | [platform-apex-logs-debug](../platform-apex-logs-debug/SKILL.md) | Deeper failure analysis |

---

## Reference File Index

| File | When to read |
|------|-------------|
| `references/cli-commands.md` | All `sf apex run test` command flags, output formats, async execution, and coverage commands |
| `references/test-patterns.md` | Test class templates — basic, bulk (251+), mock callout, and data factory patterns |
| `references/testing-best-practices.md` | Core testing principles — AAA pattern, naming conventions, bulk, negative, and mock strategies |
| `references/test-fix-loop.md` | Agentic test-fix loop implementation and failure analysis decision tree |
| `references/mocking-patterns.md` | HttpCalloutMock, DML mocking, StubProvider, and selector mocking patterns |
| `references/performance-optimization.md` | Techniques to reduce test execution time — DML mocking, SOQL mocking, loop optimizations |
| `assets/basic-test.cls` | Template: standard test class with `@TestSetup`, positive / negative / bulk / edge-case methods |
| `assets/bulk-test.cls` | Template: bulk test with 251+ records that crosses the 200-record trigger batch boundary |
| `assets/mock-callout-test.cls` | Template: HTTP callout mock using `HttpCalloutMock` |
| `assets/test-data-factory.cls` | Template: reusable `TestDataFactory` with create and insert helpers |
| `assets/dml-mock.cls` | Template: `IDML` interface + `DMLMock` implementation for database-free unit tests |
| `assets/stub-provider-example.cls` | Template: `StubProvider`-based dependency injection stub |
| `scripts/parse-test-results.py` | Post-tool hook — parses `sf apex run test` JSON output and formats failures for the auto-fix loop |

---

## Score Guide

| Score | Meaning |
|---|---|
| 108+ | strong production-grade test confidence |
| 96–107 | good test suite with minor gaps |
| 84–95 | acceptable but strengthen coverage / assertions |
| < 84 | below standard; revise before relying on it |

© forcedotcom · Apache-2.0 · forcedotcom/sf-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой