嘲笑佩斯特
我对Powershell和Pester是一个新手。我遵循了一些有关佩斯特和如何创建测试的培训,但我对此并不十分清楚。我的功能很小,可以检查在线PDF的哈希,并且已经为此写了一个测试,但是我不确定我是否以正确的方式进行操作。感谢任何帮助/解释。
测试的功能:
function Get-FileHashFromUrl {
try {
$wc = [System.Net.WebClient]::new()
Get-FileHash -InputStream($wc.OpenRead("https://example.com/apps/info.pdf"))
}
catch {
return $Error
}
}
用perster 5.3 测试
BeforeAll {
. $PSScriptRoot\myScript.ps1
}
Describe "Get-FileHashFromUrl" {
It 'Get the PDF Hash from Url' {
Mock -CommandName Get-FileHashFromUrl -MockWith { $hash }
$hash = '7EE8DB731BF3E5F7CF4C8688930D1EB079738A3372EE18C118F9F4BA22064411'
Get-FileHashFromUrl | Should -Be $hash
Assert-MockCalled Get-FileHashFromUrl -Times 1 -Exactly
}
}
I am an utter newbie regarding PowerShell and Pester. I followed some trainings about Pester and how to create tests but I am not very clear about it. I have a small function that checks the Hash of an online PDF and I have written a test for it but I am not sure if I am doing it the right way. I would appreciate any help/explanation.
Function to Test:
function Get-FileHashFromUrl {
try {
$wc = [System.Net.WebClient]::new()
Get-FileHash -InputStream($wc.OpenRead("https://example.com/apps/info.pdf"))
}
catch {
return $Error
}
}
Test with Perster 5.3
BeforeAll {
. $PSScriptRoot\myScript.ps1
}
Describe "Get-FileHashFromUrl" {
It 'Get the PDF Hash from Url' {
Mock -CommandName Get-FileHashFromUrl -MockWith { $hash }
$hash = '7EE8DB731BF3E5F7CF4C8688930D1EB079738A3372EE18C118F9F4BA22064411'
Get-FileHashFromUrl | Should -Be $hash
Assert-MockCalled Get-FileHashFromUrl -Times 1 -Exactly
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定我会使用 mock 在测试中函数,因为模拟允许您使用要伪造或更改现有命令的行为/返回数据,我想您想真正测试文件hash而不是伪造它。
如果您想故意测试故障(例如,通过获取模拟命令返回错误的哈希)或模拟无法在特定环境中运行的命令,则模拟会很有用。
假设删除了模拟函数,您的测试将无法正常工作,因为您的
get-filehashfromurl
函数正在返回get-filehash
返回的完整对象,而不是返回哈希:您要么想更改功能以返回哈希,例如:
或,将测试更改为:
I'm not sure I'd be using the Mock function in your test as mocking allows you to fake or alter the behavior/returned data of an existing command and I'm guessing you want to really test the file hash returned rather that faking it.
Mocking would be useful if you wanted to purposely test a failure for example (by getting the mocked command to return the wrong hash), or to simulate a command that you can't run in a particular environment.
Assuming that the mocked function was removed, your test wouldn't work quite as expected because your
Get-FileHashFromUrl
function is returning the complete object thatGet-FileHash
returns rather than just the hash:You'd either want to change your function to return just the hash, like so:
Or, change your test to: