用佩斯特5.3.3进行测试
我已经写了一个函数来编写在CSV文件中函数中发生的错误,此功能在我的函数的捕获块中调用。我想在佩斯特(Pester)写一项测试,以检查我的功能是否正常工作,但是老实说我不知道从哪里开始,我尝试了一些事情,但它们对我不起作用,我也一直在阅读文档但我仍然不清楚,我将感谢任何帮助/评论。
这是我想在佩斯特(Pester)写测试的功能:
function Write-Logs {
param (
[ValidateSet("Error")]$MessageType,
[string][Parameter(Mandatory=$true)]$Message,
$LogFilePath,
$Source
)
$CSVLogPath = Join-Path -Path $PSScriptRoot -ChildPath ".\errorslog.csv"
$CSVLogObject = [PSCustomObject] @{
Date = Get-Date
Message = $Message
MessageType = $MessageType
Source = $Source
}
$CSVLogObject | Export-Csv -Path $CSVLogPath -NoTypeInformation -Encoding UTF8 -Append
}
,所以我在捕获块中调用该功能:
catch {
Write-Logs -LogFilePath:$CSVLogPath -Message:$Error[0].Exception.Message `
-Source:"FunctionName()" -MessageType:"Error"
return
}
I have written a function to write the errors that occur in my functions in a csv file, this function is called in the catch block of my functions. I would like to write a Test in Pester to check that my function works correctly, but to be honest I don't know where to start, I have tried some things but they don't work for me, I have also been reading in the documentation but I am still not clear, I would appreciate any help/comments.
Here is the function for which I want to write a Test in Pester:
function Write-Logs {
param (
[ValidateSet("Error")]$MessageType,
[string][Parameter(Mandatory=$true)]$Message,
$LogFilePath,
$Source
)
$CSVLogPath = Join-Path -Path $PSScriptRoot -ChildPath ".\errorslog.csv"
$CSVLogObject = [PSCustomObject] @{
Date = Get-Date
Message = $Message
MessageType = $MessageType
Source = $Source
}
$CSVLogObject | Export-Csv -Path $CSVLogPath -NoTypeInformation -Encoding UTF8 -Append
}
and so I´m calling the function in the catch block:
catch {
Write-Logs -LogFilePath:$CSVLogPath -Message:$Error[0].Exception.Message `
-Source:"FunctionName()" -MessageType:"Error"
return
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
继续我的评论,这是一些代码。
首先通过实际使用
-logFilePath
参数来测试功能。这样,您可以在测试过程中将日志写入临时文件。由于默认值,您仍然可以在不-logfilepath
中使用它时使用它。测试代码:
testDrive:
是佩斯特为每个脚本块创建的临时驱动器。编写临时文件非常方便,因为佩斯特在脚本块结束时会自动清洁它。参见 pester docs 。Continuing from my comments, here is some code.
First make the function testable, by actually using the
-LogFilePath
parameter. This way you can write the log to a temporay file during testing. Due to the default value you can still use it without-LogFilePath
when calling it from normal code.Test code:
TestDrive:
is a temporary drive created by Pester for each script block. It is very convenient for writing temporary files because Pester cleans it automatically when the script block ends. See Pester docs.