假设我有一个C#Cmdlet
接受来自管道的值:
[System.Management.Automation.Parameter(Position = 0, Mandatory = true, ValueFromPipeline=true)]
public string Query
{
get { return query; }
set { query = value; }
}
private string query;
我会测试一下:
[TestMethod()]
public void ShouldReturnAnInfoObjectCollection()
{
// arrange
string query = "SELECT si_id, si_name FROM ci_infoobjects WHERE si_id=23";
InfoObjects actual = null;
GetInfoObjects cmdlet = new GetInfoObjects();
cmdlet.Query = query;
// act
IEnumerator result = cmdlet.Invoke().GetEnumerator();
while (result.MoveNext())
{
actual = ((InfoObjects)result.Current);
}
// assert
Assert.IsInstanceOfType(actual, typeof(InfoObjects));
}
我如何测试Cmdlet
通过管道接受Query
值的能力?
答案 0 :(得分:0)
如果这是你的Cmdlet:
[Cmdlet("Load" , "Item", DefaultParameterSetName="Item")]
public class LoadCommand : Cmdlet
{
private string assembly;
[Parameter(Mandatory=true, ValueFromPipeline=true, ParameterSetName="Item", Position=0, HelpMessageResourceId="LoadCmdlet_Item")]
public string Assembly
{
get { return assembly; }
set { assembly = value; }
}
protected override void ProcessRecord()
{
base.ProcessRecord();
if (File.Exists(assembly))
{
WriteObject(Assembly.LoadFrom(fileName));
return;
}
}
}
您可以编写一个将输入传递给cmdlet的测试。这是真正的cmdlet测试的地方:
[TestMethod]
public void ShouldLoadAssemblyWithFileName()
{
string asmFile = this.GetType().Module.FullyQualifiedName;
LoadCommand cmd = new LoadCommand();
cmd.Item = asmFile;
IEnumerator result = cmd.Invoke().GetEnumerator();
Assert.IsTrue(result.MoveNext());
Assert.IsTrue(result.Current is Assembly);
Assert.AreEqual(this.GetType().Assembly.FullName, ((Assembly)result.Current).FullName);
}
答案 1 :(得分:0)
Using Pipeline.Input for Powershell testing很有帮助。
配置runspace:
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
config = RunspaceConfiguration.Create();
}
创建测试:
[TestMethod()]
public void Get_InfoObjects_with_multiple_values_from_pipeline()
{
// "SELECT ..." | Get-InfoObjects ...
//
// arrange
//
string[] queries = { "SELECT * FROM ci_infoobjects WHERE si_id=23", "SELECT * FROM ci_infoobjects WHERE si_id=4" };
Command command = new Command("Get-InfoObjects");
using (Runspace runspace = RunspaceFactory.CreateRunspace(config))
{
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
foreach (string query in queries)
{
pipeline.Input.Write(query);
}
pipeline.Commands.Add(command);
//
// act
//
var actual = pipeline.Invoke();
//
// assert
//
Assert.AreEqual(1, actual.Count);
Assert.IsInstanceOfType(actual[0], typeof(System.Management.Automation.PSObject));
} // using Pipeline
} // using // Runspace
} // test