Skip to content

Commit 86862b8

Browse files
committed
docs(project_rules): 添加空值检查相关规范和Pester测试示例
添加关于PowerShell中空值检查的详细规范,包括变量是否为null、字符串是否为空、数组/哈希表是否为空的判断方法。同时补充Pester测试中针对空值的断言示例及注意事项。
1 parent c5c1115 commit 86862b8

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

.trae/rules/project_rules.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,65 @@
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 文档

0 commit comments

Comments
 (0)