Skip to content

Instantly share code, notes, and snippets.

@aetos382
Last active December 5, 2016 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aetos382/58828e028b46e1767eac to your computer and use it in GitHub Desktop.
Save aetos382/58828e028b46e1767eac to your computer and use it in GitHub Desktop.
// 本物の PSCmdlet 派生クラス
namespace CmdletTest
{
using System;
using System.Management.Automation;
[Cmdlet("Test", "PSCmdlet")]
public class TestPSCmdletCommand : PSCmdlet, IDisposable
{
protected IDatabaseConnection Connection { get; set; }
protected virtual void Initialize()
{
// 本物の DB 接続をセットアップする
this.Connection = new DatabaseConnection();
}
protected override void BeginProcessing()
{
// DB 接続を初期化する
this.Initialize();
}
protected override void ProcessRecord()
{
// this.Connection を使って DB にアクセスする
}
public void Dispose()
{
// DB 接続をクリーンアップする
}
}
}
// テストコード
var commandType = typeof(TestPSCmdletCommandWrapper);
var connection = new MockDatabaseConnection();
// 変数にテスト用の DB 接続をセットする
var sessionState = InitialSessionState.Create();
sessionState.Variables.Add(
new SessionStateVariableEntry(TestPSCmdletCommandWrapper.InternalConnectionVariableName, connection, null));
using (var runspace = RunspaceFactory.CreateRunspace(sessionState))
{
runspace.Open();
using (var powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
powershell.AddCommand(new CmdletInfo("Test-PSCmdlet", commandType));
var result = powershell.Invoke<string>();
Assert.AreEqual("Hello, PowerShell", result.Single());
}
}
// テスト用のラッパークラス
namespace CmdletTest.Tests
{
using System;
using System.Management.Automation;
internal class TestPSCmdletCommandWrapper : TestPSCmdletCommand
{
public const string InternalConnectionVariableName = "InternalDatabaseConnection";
protected override void Initialize()
{
// 変数から DB 接続を取得する
this.Connection = (IDatabaseConnection)this.SessionState.PSVariable.GetValue(InternalConnectionVariableName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment