2017-07-01 69 views
1

我现在正在使用美妙的Pester单元测试缓慢学习一段时间。我有点拘泥于检查我的函数是否可以运行“如果没有提供任何强制性输入到函数”的用法。这里给我一盏红灯,想要获得绿色测试结果并继续进行编码。Pester单元测试功能必选= True

所以我有一个功能如下。

function Code() 
{  
param(
    [parameter(Mandatory=$true)] 
    [string]$SourceLocation) 
return "Hello from $SourceLocation" 
} 

我的测试脚本与以下检查 执行...

$moduleName = 'Code'; 
Describe $moduleName {   
     Context "$Function - Returns a result " { 
      It "does something useful with just $Function function name" { 
      $true | Should Be $true 
      } 
     } 

     Context "$Function - Returns with no input " { 
     It "with no input returns Mandatory value expected" { 
      Code | Should Throw 
     } 
     } 

     Context "$Function - Returns some output" { 
      It "with a name returns the standard phrase with that name" { 
       Code "Venus" | Should Be "Hello from Venus" 
      } 
      It "with a name returns something that ends with name" { 
       Code "Mars" | Should Match ".*Mars" 
      } 
     } 

    } #End Describe 

从AppVeyor我的输出显示了这个结果的是[+]是绿色的色彩和[ - ]为红色这正是我所能避免的最好的。

Describing Code 
    Context Code - Returns a result 
     [+] does something useful with just Code function name 16ms 
    Context Code - Returns with no input 
     [-] with no input returns Mandatory value expected 49ms 
     Cannot process command because of one or more missing mandatory parameters: SourceLocation. 
     at <ScriptBlock>, C:\projects\code\Code.Tests.ps1: line 117 
     117:   Code | Should Throw 

    Context Code - Returns some output 
     [+] with a name returns the standard phrase with that name 23ms 
     [+] with a name returns something that ends with name 11ms 

任何帮助表示赞赏,因为我想一个绿色的条件那里我不知道如何从Powershell的克服某些类型的消息响应并转化为单元测试这个...

+2

['应该'测试投掷和不投掷需要一个脚本块作为输入](https://github.com/pester/Pester/wiki/Should#throw)所以尝试'{Code} |应该投掷吗? – TessellatingHeckler

+0

哦,你知道什么...它的作品!谢谢你@TessellatingHeckler –

回答

2

每从TessellatingHeckler需要管Should cmdlet的一个脚本块{ }发表评论,你的代码是不是为了测试Throw因为工作:

{Code} | Should Throw 

值得一提的是不过时(TESTIN g代表强制性参数),因为PowerShell在非交互式控制台(PowerShell.exe -noninteractive)中运行,所以在AppVeyor中运行正常。如果您尝试在本地运行Pester测试,您的测试看起来会在您提示输入时中断。

有一对夫妇的解决这个办法,一个是刚刚运行测试本地非交互模式下使用PowerShell的:

PowerShell.exe -noninteractive {Invoke-Pester} 

另一个是传递参数的明确$null或空值(需要提醒的是实际上你可以有一个接受$null强制性字符串参数和该解决方案不会与所有其他参数类型一定工作):

It "with no input returns Mandatory value expected" { 
    {Code $null} | Should Throw 
} 

然而,值得注意的是,这两种解决方案抛出不同的异常消息,并且您应该进一步测试Throw的显式消息,以便在代码由于某些其他原因而失败时不通过测试。例如:

与-nonInteractive

It "with no input returns Mandatory value expected" { 
    {Code} | Should Throw 'Cannot process command because of one or more missing mandatory parameters: SourceLocation.' 
} 

跑步传递$空

It "with no input returns Mandatory value expected" { 
    {Code $null} | Should Throw "Cannot bind argument to parameter 'SourceLocation' because it is an empty string." 
} 

总之这只是因为你的参数这种特定情况下一个复杂的问题是强制性的,你正在测试它的缺席。

测试例外一般是一个简单的过程:

{ some code } | should Throw 'message' 

而且在两者的交互式和非交互式控制台工作正常。