Powershell 5类的Pester模拟方法 [英] Pester mock method for Powershell 5 class

查看:70
本文介绍了Powershell 5类的Pester模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试模拟Powershell 5类方法时遇到问题,执行测试时,出现错误"CommandNotFoundException:找不到Command FunctionToMock".我试图通过模拟"FunctionToMock"对"OutputToOverwrite"方法进行单元测试.我想我必须首先模拟ChocoClass本身,但是我不确定该怎么做.谢谢.

I am having an issue trying to mock a powershell 5 class method, when executing the test, I get the error " CommandNotFoundException: Could not find Command FunctionToMock". I am trying to unit test the "OutputToOverwrite" method by mocking "FunctionToMock". I think I would have to mock ChocoClass itself first, but I am not sure how to do it. Thanks.

Class ChocoClass
{
    [string] OutputToOverwrite()
    {
        return $this.FunctionToMock()
    }

    [string] FunctionToMock()
    {
        return "This text will be replaced"
    }
}


Describe "Testing mocking"{
    it "Mock test"{
        Mock FunctionToMock -MockWith {return "mystring"}
        $package = New-Object ChocoClass
        $expected = $package.OutputToOverwrite()
        $expected | should BeExactly "mystring"
    }
}

推荐答案

我已经看到了两种方法:

I have seen two ways to do this:

  1. 将大部分实现隔离为一个函数.
  2. 从类继承并重写方法.

(1)使用函数

我一直将方法的实现分为如下功能:

(1) Use a Function

I have been separating the implementation of methods into functions like this:

Class ChocoClass
{
    [string] OutputToOverwrite()
    {
        return $this.FunctionToMock()
    }

    [string] FunctionToMock()
    {
        return FunctionToMock $this
    }
}

function FunctionToMock
{
    param($Object)
    return "This text will be replaced"
}

有了这一更改,您的测试就可以在我的计算机上通过.这避免了与PowerShell类有关的陷阱,也避免了测试类行为.

With that change, your test passes on my computer. This avoids PowerShell-class-related pitfalls but also avoids testing class behavior.

您可以派生该类并覆盖您要模拟的方法:

You can derive the class and override the method you want to mock:

Describe "Testing mocking"{
    it "Mock test"{
        class Mock : ChocoClass {
            [string] FunctionToMock() { return "mystring" }
        }
        $package = New-Object Mock
        $expected = $package.OutputToOverwrite()
        $expected | should BeExactly "mystring"
    }
}

此测试在我的计算机上通过.我尚未将这种方法用于生产代码,但是我喜欢它的直接性.请注意与在单个PowerShell会话中重新定义同名类有关的问题(请参见下面的附带说明).

This test passes on my computer. I haven't used this method for production code yet, but I like how direct it is. Watch out for problems related to re-defining classes with the same name in a single PowerShell session (see side note below).

旁注:(1)的分隔使我遇到的

Side note: The separation of (1) minimizes the amount I run into this bug that prevents classes from being reloaded when you make changes to them. I have found, though, that the better workaround is to invoke each test run in a new PowerShell session (e.g. PS C:\>powershell.exe -Command { Invoke-Pester }) so I'm leaning toward (2) now.

这篇关于Powershell 5类的Pester模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆