Last active
December 5, 2016 06:39
-
-
Save aetos382/58828e028b46e1767eac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 本物の 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 接続をクリーンアップする | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// テストコード | |
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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// テスト用のラッパークラス | |
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