Search code examples
c#powershell-cmdlet

How to test a value supplied via the pipeline to a C# cmdlet


Assuming that I have a C# Cmdlet that accepts values from the pipeline:

[System.Management.Automation.Parameter(Position = 0, Mandatory = true, ValueFromPipeline=true)]
public string Query
{
    get { return query; }
    set { query = value; }
}
private string query;

I would test this:

[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));

}

How would I test this Cmdlet's ability to accept a value for Query via the pipeline?


Solution

  • Using Pipeline.Input for Powershell testing was helpful.

    Configure runspace:

    [ClassInitialize()]
    public static void MyClassInitialize(TestContext testContext)
    {
        config = RunspaceConfiguration.Create();
    }
    

    Create test:

    [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