2017-07-01 101 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' 

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