简体   繁体   English

如何将参数传递给PSUnit测试脚本?

[英]How do I pass parameters to a PSUnit test script?

I am using PSUnit for testing purposes in Powershell 2.0. 我将PSUnit用于Powershell 2.0中的测试目的。 Because my tests need to connect to a database server I would like to be able to pass the server and database name into the test script. 因为我的测试需要连接到数据库服务器,所以我希望能够将服务器和数据库名称传递到测试脚本中。 This would then allow developers to run the test scripts on their local machine with a local database while at the same time making it possible to run it on a server. 然后,这将使开发人员可以在具有本地数据库的本地计算机上运行测试脚本,同时可以在服务器上运行测试脚本。 The database may also change depending on the environment. 数据库也可能根据环境而变化。

The PSUnit.Run script doesn't seem to allow you to include parameters with the test script name. PSUnit.Run脚本似乎不允许您在测试脚本名称中包含参数。 Have I missed anything? 我错过了什么吗? Is there a workaround for this? 有没有解决方法?

Thanks! 谢谢!

The only way that I was able to find to do this was to include tags at the start of my test script, then search and replace the correct values in place of those tags. 我能找到的唯一方法是在测试脚本的开头包含标签,然后搜索并替换正确的值来代替这些标签。 For example, in my case my test script included this code at the top of the script: 例如,就我而言,我的测试脚本在脚本顶部包含以下代码:

[string]$ServerName=<ServerName>
[string]$TargetDatabaseName=<TargetDatabaseName>

That is the literal code. 那就是文字代码。 Then, in my script where I called the tests I included this code: 然后,在调用测试的脚本中,我包含了以下代码:

foreach ($testPSScript in Get-ChildItem "$testScriptDir\*.ps1") {
    (Get-Content $testPSScript.FullName) |
    ForEach-Object {$_ -replace "<ServerName>", "'$ServerName'"} |
    ForEach-Object {$_ -replace "<TargetDatabaseName>", "'$DatabaseName'"} |
    Set-Content $testPSScript.FullName -Force

    PSUnit.Run.ps1 -PSUnitTestFile "$testPSScript"
}

You have to remember to overwrite your test script(s) with the original version each time, otherwise it will include the values that you used in your last run instead of the tags and you won't be able to change the values. 您必须记住每次都用原始版本覆盖测试脚本,否则它将包含您在上次运行中使用的值而不是标签,并且您将无法更改这些值。

Why don't you just include the 2 variables ( [string]$ServerName & [string]$TargetDatabaseName ) in 'profile.ps1' file & use these in your test cases. 为什么不在'profile.ps1'文件中仅包含2个变量( [string]$ServerName[string]$TargetDatabaseName )并在测试用例中使用它们。 These would be available there and you can configure them anytime in the ps1 file. 这些将在那里可用,您可以随时在ps1文件中对其进行配置。

This seems to be easier & more intuitive than writing a separate script for this task. 与为该任务编写单独的脚本相比,这似乎更容易且更直观。

Just append any such info to PowerShell profile. 只需将任何此类信息附加到PowerShell配置文件即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM