SkillπEnglish
← 返回目录
deepskill

Pester 跨主版本测试迁移

pester-migration

授权

用于跨主版本升级 PowerShell Pester 测试套件的迁移技能:v3→v4、v4→v5 和 v5→v6。覆盖 Discovery/Run 两阶段模型、将初始化移入 BeforeAll、$PSScriptRoot 与 $MyInvocation 的比较、mock 变更(Assert-MockCalled → Should -Invoke、移除回落行为)、Invoke-Pester 参数到 PesterConfiguration、数据驱动的 -ForEach/-TestCases,以及 v6 的破坏性变更。当用户要求升级、迁移或现代化 Pester 测试、修复升级 Pester 版本后失效的 *.Tests.ps1 文件,或转换旧版 Should/Invoke-Pester 语法时使用。

↓ 0 下载 ↗ 0 分享点击

介绍来源: author · github · b6483db44fb602654bca6a097185fcaddb305f97 参考来源

作者原文

Pester migration skill for upgrading PowerShell Pester test suites across major versions — v3→v4, v4→v5, and v5→v6. Covers the Discovery/Run two-phase model, moving setup into BeforeAll, $PSScriptRoot vs $MyInvocation, mock changes (Assert-MockCalled → Should -Invoke, removed fall-through), Invoke-Pester parameters → PesterConfiguration, data-driven -ForEach/-TestCases, and the v6 breaking changes. Use when the user asks to upgrade, migrate, or modernize Pester tests, fix *.Tests.ps1 files that broke after bumping the Pester version, or convert legacy Should / Invoke-Pester syntax.

SkillPi 解读

能完成的任务
Pester 跨主版本测试迁移
适合谁
请按作者原文中的适用场景判断。
输入和输出
以作者完整文档为准;本站未运行验证产物。
软件、账号及付费要求
使用前按完整文档确认软件、账号、费用及权限;由宿主核对并授权实际文件读写和外部服务。文档引用域名(非运行白名单):gist.github.com, github.com, pester.dev
限制与区别
原文中的功能、版本状态和效果描述属于作者陈述;中文为对应翻译。仅核对固定版本及静态附件证据,不保证运行效果、外部服务或兼容性。
实测状态
未测试

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 读取本地文件

    限定到你选择的文件或项目目录;避免读取无关的个人资料、密钥和配置文件。

    主文档提及 · 第 110 行
文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • pester.dev

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

caution · 静态证据核验,不代表运行安全保证。

使用前按完整文档确认软件、账号、费用及权限;由宿主核对并授权实际文件读写和外部服务。文档引用域名(非运行白名单):gist.github.com, github.com, pester.dev

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。

原始 SKILL.md

---
name: pester-migration
description: 'Pester migration skill for upgrading PowerShell Pester test suites across major versions — v3→v4, v4→v5, and v5→v6. Covers the Discovery/Run two-phase model, moving setup into BeforeAll, $PSScriptRoot vs $MyInvocation, mock changes (Assert-MockCalled → Should -Invoke, removed fall-through), Invoke-Pester parameters → PesterConfiguration, data-driven -ForEach/-TestCases, and the v6 breaking changes. Use when the user asks to upgrade, migrate, or modernize Pester tests, fix *.Tests.ps1 files that broke after bumping the Pester version, or convert legacy Should / Invoke-Pester syntax.'
---

# Pester Migration

Pester is the test framework for PowerShell. Test files end in `*.Tests.ps1` and use
`Describe` / `Context` / `It` blocks with `Should` assertions. This skill upgrades an existing
suite from one major Pester version to the next and gets it green again.

> **Mental model:** each major jump has a different character. **v3→v4** is mostly a syntax
> rename. **v4→v5** is a *fundamental runtime change* (the Discovery/Run split) and is the hard
> one. **v5→v6** is largely backwards-compatible — a handful of previously-deprecated things now
> throw. Migrate **one major at a time**; never skip a version.

Detailed, symptom-driven guides live in `references/` — load the one(s) for the jump you are doing.

## References

| Reference | When to load |
|---|---|
| [v3-to-v4.md](references/v3-to-v4.md) | `Should Be` → `Should -Be`, `Contain` → `FileContentMatch`, `Assert-VerifiableMocks` → `Assert-VerifiableMock`, array-assertion edge cases. |
| [v4-to-v5.md](references/v4-to-v5.md) | The big one. Discovery/Run phases, `BeforeAll` setup, `$PSScriptRoot`, `BeforeDiscovery`, `-ForEach`, mock scoping, `Should -Throw` wildcards, `Invoke-Pester` → `New-PesterConfiguration`. |
| [v5-to-v6.md](references/v5-to-v6.md) | PowerShell 5.1/7.4+ only, per-file discovery+run, empty `-ForEach` throws, duplicate setup blocks throw, name `<...>` templates evaluate, `Assert-MockCalled` removed, mocks no longer fall through, code-coverage tracer, legacy `Invoke-Pester` params removed. |

Canonical source: the official migration guides at https://pester.dev/docs/migrations/ — this skill
mirrors them. When in doubt, prefer the website.

## Step 0 — Detect where you are and where you're going

Find the installed version(s) and the version the **tests** were written for. These can differ.

```powershell
# Installed Pester version(s) on this machine
Get-Module Pester -ListAvailable | Select-Object Name, Version, Path

# Version currently imported in the session
(Get-Module Pester).Version
```

Tell the source version from the **test code** with these heuristics:

| You see in `*.Tests.ps1` / build scripts | Suite was written for |
|---|---|
| `Should Be` / `Should Contain` (no dash) | v3 or earlier → start at [v3-to-v4](references/v3-to-v4.md) |
| `$MyInvocation.MyCommand.Path` + dot-source at the **top** of the file; arbitrary code directly under `Describe` | v4 → [v4-to-v5](references/v4-to-v5.md) |
| `Assert-MockCalled`, `Assert-VerifiableMock`, `Set-ItResult -Pending` | v4 / early-v5 (these are **removed in v6**) |
| `Invoke-Pester -Script … -OutputFile … -CodeCoverage …` (legacy params) | v4 invocation → map to config |
| `BeforeAll { . $PSScriptRoot/… }`, `New-PesterConfiguration`, `Should -Invoke` | already v5-style → [v5-to-v6](references/v5-to-v6.md) |

Install the target version when ready:

```powershell
# Latest stable v5 — pin the major to avoid installing Pester 6
Install-Module Pester -MaximumVersion 5.99.99 -Force

# Pester 6
Install-Module Pester -Force
```

> On **Windows PowerShell 5.1** the OS ships a Microsoft-signed built-in Pester 3 that PowerShellGet
> won't overwrite with the differently-signed newer Pester — add `-SkipPublisherCheck` there to
> install side-by-side. Not needed on PowerShell 7+. See
> https://pester.dev/docs/introduction/installation.

## Migration workflow

Run this loop for each major jump. **Do not jump two majors at once** — go v4→v5, then v5→v6.

1. **Baseline.** Run the suite on the **current** version first and record pass/fail. You need a
   known-good (or known) starting point so you can tell migration regressions apart from
   pre-existing failures.
   ```powershell
   # Bare Invoke-Pester works on every major; exact parameters differ
   # (v3/v4: -Script/-OutputFile; v5+/v6: -Path/-Output).
   Invoke-Pester
   ```
2. **Read the reference** for this jump (table above) so you know the full scope before editing.
3. **Edit file by file.** Apply the mechanical changes (see per-jump cheat sheets below and in the
   reference). Keep changes small and reviewable — one file or one concern at a time.
4. **Switch versions** with `Install-Module` (Step 0), then re-import: `Remove-Module Pester;
   Import-Module Pester` (or start a fresh session).
5. **Run and fix.** Re-run with `-Output Detailed`; use `-Output Diagnostic` (v4→v5) or read the
   explicit v6 error messages to locate problems. Match each failure to the **symptom → fix**
   tables in the reference.
6. **Green, diff, commit.** Re-run until the result matches the baseline (or better). Review the
   diff, then commit. Migrating in small commits makes regressions trivial to bisect.

## What actually changes (scope per jump)

| Jump | Difficulty | Nature |
|---|---|---|
| v3 → v4 | Low | Assertion-syntax rename (`Should -Be`). Largely script-automatable. |
| v4 → v5 | **High** | New two-phase runtime. Test **structure** changes: setup must move into `BeforeAll`, discovery-time code into `BeforeDiscovery`, file location via `$PSScriptRoot`. Not a pure find-replace. |
| v5 → v6 | Low–Medium | Backwards-compatible runtime; deprecated features now throw. Mostly small, targeted fixes. Your `Should -Be` assertions keep working unchanged. |

## Quick cheat sheets

### v4 → v5 (most common fixes)
```powershell
# 1. Move file import into BeforeAll, use $PSScriptRoot (NOT $MyInvocation.MyCommand.Path)
# BEFORE
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\Get-Thing.ps1"
# AFTER
BeforeAll { . $PSScriptRoot/Get-Thing.ps1 }

# 2. Any code that DISCOVERS/generates tests must be in BeforeDiscovery
BeforeDiscovery { $cases = Get-Content $PSScriptRoot/cases.json | ConvertFrom-Json }

# 3. Should -Throw matches with -like wildcards, not .Contains
{ throw 'a long message' } | Should -Throw '*long*'

# 4. Invoke-Pester legacy params → New-PesterConfiguration (see reference for full map)
```
Full details, scoping rules, and the parameter→config table: [references/v4-to-v5.md](references/v4-to-v5.md).

### v5 → v6 (most common fixes)
```powershell
# 1. Mock assertions: removed verbs — rename (old -> new):
#    Assert-MockCalled     -> Should -Invoke
#    Assert-VerifiableMock -> Should -InvokeVerifiable
Should -Invoke Get-Thing -Times 1 -Exactly
Should -InvokeVerifiable

# 2. Add a default mock — unmatched calls no longer run the real command
Mock Get-Thing { 'default' }
Mock Get-Thing -ParameterFilter { $Name -eq 'a' } -MockWith { 'a' }

# 3. Empty/$null -ForEach now throws; allow it only where empty is expected
Describe 'Optional' -ForEach $cases -AllowNullOrEmptyForEach { }

# 4. Combine duplicate BeforeAll/BeforeEach/AfterAll/AfterEach in the same block into one
```
Full breaking-change list with symptoms and fixes: [references/v5-to-v6.md](references/v5-to-v6.md).

## Safety rules

- **Tests are the spec.** Migration must not change what a test asserts — only how the suite is
  structured and invoked. If a test starts passing/failing differently for any reason other than a
  documented breaking change, investigate before accepting it.
- **Automated migration scripts produce false positives.** The community scripts (linked in the
  references) help with `Should` syntax and dot-sourcing, but always review the diff and re-run the
  suite afterward. Never bulk-edit and commit unchecked.
- **Mind file encoding** when scripting replacements over `*.Tests.ps1` — preserve the original
  encoding (UTF-8 vs ASCII) so you don't mangle non-ASCII test names.
- **Work on a branch, commit per file/concern.** Small commits keep `git bisect` useful if a
  migrated test goes red later.

版权与许可声明

MIT License

Copyright GitHub, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.