File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 100100- 使用 Pester 框架进行单元测试
101101- 测试覆盖主要功能和边界情况
102102
103+ ### 空值检查
104+
105+ #### ** 1. 检查一个变量是否就是 ` null ` **
106+
107+ ** 做法:** 把 ` $null ` 放在左边比较。
108+
109+ ``` powershell
110+ if ($null -eq $myVar) { ... }
111+ ```
112+
113+ ** 场景:** 只关心变量是不是 ` null ` ,不关心它是不是空字符串或空数组。
114+
115+ #### ** 2. 检查一个字符串是否“没有内容”**
116+
117+ ** 做法:** 使用 ` [string]::IsNullOrWhiteSpace() ` 。
118+
119+ ``` powershell
120+ if ([string]::IsNullOrWhiteSpace($myString)) { ... }
121+ ```
122+
123+ ** 场景:** 需要判断字符串是 ` null ` 、空 (` "" ` ) 还是只有空格。
124+
125+ ---
126+
127+ #### ** 3. 检查一个数组或哈希表是否为空**
128+
129+ ** 做法:** 检查 ` .Count ` 属性是否为 ` 0 ` 。
130+
131+ ``` powershell
132+ if ($myArray.Count -eq 0) { ... }
133+ ```
134+
135+ ** 场景:** 确定一个集合里没有任何元素。** 切勿** 用 ` if (-not $myArray) ` ,因为空数组在布尔判断中是 ` true ` 。
136+
137+ ---
138+
139+ #### ** 4. 检查一个变量是 ` null ` 或空数组**
140+
141+ ** 做法:** 使用 ` @() ` 强制转换为数组再检查 ` .Count ` 。
142+
143+ ``` powershell
144+ if (@($myVar).Count -eq 0) { ... }
145+ ```
146+
147+ ** 场景:** 函数可能返回 ` null ` 或一个空数组,你希望两种情况都当成“空”来处理。
148+
149+ ---
150+
151+ ### ** Pester 测试中的规则 (` .Tests.ps1 ` )**
152+
153+ | 检查目标 | Pester 断言 |
154+ | :------------------------ | :----------------------------------------- |
155+ | ** 是 ` $null ` ** | `($variable) | Should -Be $null` |
156+ | ** 不是 ` $null ` ** | `($variable) | Should -Not -Be $null` |
157+ | ** 是空数组/空字符串** | `$variable | Should -BeEmpty` |
158+ | ** 是 ` $null ` 或空** | `($variable) | Should -BeNullOrEmpty` |
159+
160+ ** 为什么要有括号?** 防止当变量是空数组时,PowerShell 管道“吞掉”它,导致 ` Should ` 命令收不到任何东西而报错。括号能确保数组对象本身被传递。
161+
103162## 文档规范
104163
105164### README 文档
You can’t perform that action at this time.
0 commit comments