Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
// 本物の 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