首页 > 解决方案 > 如何使用 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

有没有解决这个问题的好方法?我的想法不多了。

提前感谢任何阅读此问题的人。

标签: c#powershellunit-testingpester

解决方案


为什么不写入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
    }
}

这将创建一个模拟生产的实际文件,以便您可以正确测试它。


推荐阅读