c# - 如何使用 Pester 模拟 .cs 文件的内容,允许我遍历每一行和每个字符?
问题描述
简短的介绍:
我正在尝试使用 Pester 模拟文件的内容,然后遍历该假数据的每一行和每个字符,但我收到此错误:“数组索引评估为空。” 当试图访问一行的字符时。
背景:
我有一个读取 global.asax.cs 文件内容的 Powershell 函数。
我正在读取的文件示例:
namespace MockData
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
}
}
}
然后,我的函数将使用 Get-Content 读取文件并遍历每一行和每个字符。示例(简化版本, $index 变量在此示例中看起来很讨厌,但在实际代码中需要它):
$contents = Get-Content $filePath
$index = 0
$bracketCounter = 0
Do {
foreach($char in $contents[$index].ToCharArray()) {
if($char -eq "{") {
$bracketCounter++
}
elseif ($char -eq "}") {
$bracketCounter--
}
}
$index++
} While ($bracketCounter -gt 0)
现在在 Pester 中,这是我的测试代码:
It "check for success" {
Mock Get-Content {
$content = "namespace MockData
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
}
}
}"
return $content
} -ParameterFilter { $Path -like "*asax*"}
[string[]]$errors = MyPowershellFile
$errors | should BeNullOrEmpty
}
预期成绩:
我的预期结果是,Pester 测试以与真实内容相同的方式迭代模拟内容。
调用此行时发生 Pester 的错误:
foreach($char in $contents[$index].ToCharArray())
我得到“RuntimeException:索引操作失败;数组索引评估为空。”
我认为这是因为在真正的函数中,$contents 的第一个元素是文件的第一行。
$contents[0] = namespace MockData
而在 Pester 函数中,$contents 的第一个元素是第一个字符。
$contents[0] = n
有没有解决这个问题的好方法?我的想法不多了。
提前感谢任何阅读此问题的人。
解决方案
为什么不写入TestDrive然后模拟:
Describe 'test things' {
#create a here-string and write the contents to the testdrive
@"
namespace MockData
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
}
}
}
"@ | Set-Content -Path TestDrive:\testfile.txt
#Set up the mock to get-content
Mock Get-Content {
Get-Content TestDrive:\testfile.txt
} -ParameterFilter {$path -like "*asax*"}
#make sure the content matches
it "finds strings in mocked content" {
Get-Content abc.asax | Select-String MVCHandler | Should -Match 'MvcHandler.DisableMvcResponseHeader = true;'
}
#make sure the line count is correct
it 'should have 10 lines of content' {
(Get-Content def.asax).Count | Should -BeExactly 10
}
#make sure our mock was called the correct number of times
it "called mocked get-content twice" {
Assert-MockCalled Get-Content -Times 2
}
}
这将创建一个模拟生产的实际文件,以便您可以正确测试它。
推荐阅读
- python - 如何在逻辑回归中进行拟合?
- r - 将 ggplot 对象存储为 R 数据框中的元素时出错
- php - 检查自定义帖子类型类别中是否已存在帖子名称
- javascript - 返回的主键整数在查找时递增
- python-3.x - 如何在 python folium 地图上添加点击事件
- javascript - 尝试设置窗口高度,但在 react.js 中出现错误
- powerbi - Power Bi 中的循环依赖
- php - Wordpress,从模板部分调用类方法
- mysql - mysql 如何将mysql选择结果的列转换为行
- flutter - 将上下文传递给 showdialog,以便在开始页面加载时不会丢失