如何正确地纠缠测试导入-Clixml



所以首先我需要声明我对 Pester 很陌生,可能没有正确编写我的测试或没有正确理解它的所有功能。

所以背景是我想用 Pester 自动化我的 PowerShell 模块,到目前为止已经编写了一些测试。

我的模块的一部分是将配置内容保存在 clixml 文件中。我想编写一组测试,以确保保存和获取配置按预期工作。

基本上我有一个功能来保存配置文件,还有一个函数来检索它。我的纠缠器测试如下所示:

BeforeAll{
if(Test-path existingconfigfile.xml){
Rename-Item -Path "existingconfigfile" -NewName "backup.xml"
}
Save-configfunction -param1 'Value1' -param2 'Value2'
#saves as test.xml
}
Afterall{
if(Test-path backup.xml){
# Remove mocked test file
Remove-Item -Path "test.xml" -Force
# Place original back
Rename-Item -Path "backup.xml" -NewName "existingconfigfile.xml"
}
}
it "importconfig should return expected values for mocked object" {
{
$result = Get-config
$result
$result.Containsvalue('Value1') | Should be $true
}
}

现在我已经尝试了it块的几种变体:

it "importconfig should return expected values for mocked object" {
{
$result = Get-config
$result.param1 | Should be "Value1"
}
}
it "importconfig should return expected values for mocked object" {
$result = Get-Config
$result | Should match 'Value1'
$result | Should match 'Value2'
}
it "importconfig should return expected values for mocked object" {
$result = Get-Config
$result.Param1 | Should match 'Value1'
$result.Param2 | Should match 'Value2'
}

Pester 总是返回通过的测试,即使我将匹配值更改为不正确的值。佩斯特在所有情况下都这样做。因此,由于某种原因,Pester 没有正确限定值,并且总是返回正结果。

所以我想知道我做错了什么。显然,如果值实际匹配,Pester 应该通过测试,但如果它们不匹配,它应该失败。

我认为与其使用BeforeAllAfterAll来创建Mock类型行为来修改配置,不如使用实际的Mock语句。这就是我的意思(我已经创建了简单的表示,我假设你的函数做了什么,因为你没有共享它们(:

function Set-Config {
Param(
$Config
)
$Config | Export-Clixml C:Tempproduction_config.xml
}
function Get-Config {
Import-Clixml C:Tempproduction_config.xml
}
Describe 'Config function tests' {
Mock Set-Config {
$Config | Export-Clixml TestDrive:test_config.xml
}
Mock Get-Config {
Import-Clixml TestDrive:test_config.xml
}
$Config = @{
Setting1 = 'Blah'
Setting2 = 'Hello'
}
It 'Sets config successfully' {
{ Set-Config -Config $Config } | Should -Not -Throw
}
$RetrievedConfig = Get-Config
It 'Gets config successfully' {
$RetrievedConfig.Setting1 | Should -Be 'Blah'
$RetrievedConfig.Setting2 | Should -Be 'Hello'
}
}

这将创建Get-ConfigSet-Config函数的模拟,将配置的写入/读取重定向到 TestDrive:\,这是 Pester 提供并在之后自动清理的特殊临时磁盘区域。

请注意,这仅在测试使用这些函数的父函数时才有意义。如果您正在编写Get-ConfigSet-Config函数本身的测试,那么您反而希望模拟Export-CliXmlImport-CliXml命令。

最新更新