powershell Pester不反映脚本中的更改

58wvjzkj  于 2023-06-06  发布在  Shell
关注(0)|答案(1)|浏览(490)

我使用的是Pester版本:5.3.3,不太确定我是否正确。我只有一个包含整个逻辑的文件:Function.Tests.ps1.

BeforeAll{
 import-module .\Function.Tests.ps1 -Force
 Remove-Item -Path "$PSScriptRoot\testresults.xml" -ErrorAction SilentlyContinue
}

Describe "Test CreateNewTable Function" {
Push-Location
Import-Module sqlserver -DisableNameChecking
Pop-Location

$tableName = 'xxx'
$instance = "myServer"
$dbcmd = @"
SELECT [Name] AS TableName 
  FROM [sys].[tables] 
 WHERE [Name] = '$($tableName)'
"@
 $result = Invoke-Sqlcmd -Query $dbcmd `
                      -ServerInstance $instance `
                      -Database 'master' `
                      -SuppressProviderContextWarning
 It "$tableName should exist" {
   ($result.TableName -eq $tableName) | Should -Be $true
 }
}

当我第一次运行测试时,表“xxx”就位,一切正常,我得到了-正如预期的-一条成功消息:

Invoke-Pester .\Function.Tests.ps1

但是当我修改脚本时,输入了一个错误的表名,比如“yyy”,我期待着一个错误,但是什么也没有发生,我仍然得到一个成功的消息。奇怪的是,当我将服务器名称更改为错误的名称时,Pester会反映出该更改,我会得到一个错误,但是将dbname更改为错误的名称仍然会成功。
我创建了两个单独的文件:功能和测试单元。功能:

Function Get-Table
{  
param(
       [string]$tableName,
       [string]$instance,
       [string]$database
)
$dbcmd = @"
SELECT [Name] AS TableName 
  FROM [sys].[tables] 
 WHERE [Name] = '$($tableName)'
"@
return $result = Invoke-Sqlcmd -Query $dbcmd `
                      -ServerInstance $instance `
                      -Database $database `
                      -SuppressProviderContextWarning
}

测试单元:

BeforeAll{
. $PSScriptRoot/Get-Table.ps1
}
Describe "Test CreateNewTable Function" {
Import-Module sqlserver -DisableNameChecking
$tableName = 'clusters'
$instance = "xxx"
$database = "YYY"
$result = Get-Table -tableName $tableName -instance $instance - 
database $database
# Now run the test   
It "$tableName should exist" {
    ($result.TableName -eq $tableName) | Should -Be $true
    }
}

两个文件都在同一个目录中,调用test:

Invoke-Pester C:\PesterTests\Function.Tests.ps1

我仍然会得到错误:
C:\PesterTests\Function.Tests.ps1中的发现失败,原因为:System.Management.Automation.CommandNotFoundException:术语“Get-Table”无法识别为cmdlet的名称,函数意味着将不会加载函数文件,并且函数Get-Table未知。

mfuanj7w

mfuanj7w1#

解决办法很简单:你不能把逻辑放在describe-block中(就像我做的那样),只要我把逻辑放在“it”块中,它就工作了!

BeforeAll {
. $PSScriptRoot/Get-Table.ps1
}
Describe 'Get-Table' {
It "$tableName should exist" {
  Push-Location
  Import-Module sqlserver -DisableNameChecking
  Pop-Location
  $tableName = 'cluster'
  $instance = "xxx"
  $database = "YYY"
  $result = Get-Table -tableName $tableName -instance $instance -database 
  $database
  $result.TableName -eq $tableName | Should -Be $true
  }
}

相关问题