2017-08-29 92 views
3

我試圖找出如何有參數糾纏測試缺少強制參數:測試與糾纏

查找-Waldo.Tests.ps1

$here = Split-Path -Parent $MyInvocation.MyCommand.Path 
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 

Describe 'Mandatory paramters' { 
    it 'ComputerName' { 
     { 
      $Params = @{ 
       #ComputerName = 'MyPc' 
       ScriptName = 'Test' 
      } 
      . "$here\$sut" @Params 
     } | Should throw 
    } 
} 

Find- Waldo.ps1

Param (
    [Parameter(Mandatory)] 
    [String]$ComputerName, 
    [String]$ScriptName 
) 

Function Find-Waldo { 
    [CmdletBinding()] 
    Param (
     [String]$FilePath 
    ) 

    'Do something' 
} 

每次我試圖assert結果或乾脆運行TES t,它會提示我輸入ComputerName參數,而不是通過測試。

我在這裏錯過了一些超級明顯的東西嗎?有沒有辦法測試強制參數的存在?

+1

你不應該試圖以這種方式來測試'Mandatory'屬性,[按照從球隊本評論](https://開頭的github (Get-Command Get-Command).Parameters ['Name']。Attributes |?{$ _ -/PowerShell/PowerShell/issues/2408#issuecomment-251140889) –

+0

可以給出一個關於如何使用'是[參數]})。必須|在上面的例子中,腳本應該是$ false? – DarkLite1

+2

'Get-Command'也可以在腳本文件上運行:'(Get-Command「$ here \ $ sut」)。參數' –

回答

1

根據Mathias的評論,您無法真正測試是否缺少Mandatory參數,因爲PowerShell會提示輸入而不是引發錯誤。每comment he linked to from the Pester team你可以使用Get-Command來測試腳本強制性參數設置:

((Get-Command "$here\$sut").Parameters['ComputerName'].Attributes.Mandatory | Should Be $true 

另一種選擇是在這種情況下不使用強制參數,而是有一個腳本塊,做了Throw作爲該參數的默認值:

Param (
    [String]$ComputerName = $(Throw '-ComputerName is required'), 
    [String]$ScriptName 
) 

如果腳本始終用作一個自動化過程(經由代替用戶執行),這可能是優選的,因爲它允許你控制/捕獲其行爲,並且避免了它的一部分執行期間卡住了。然後,您可以測試測試腳本,你最初提出:

Describe 'Mandatory paramters' { 
    it 'ComputerName' { 
     { 
      $Params = @{ 
       #ComputerName = 'MyPc' 
       ScriptName = 'Test' 
      } 
      . "$here\$sut" @Params 
     } | Should throw '-ComputerName is required' 
    } 
}