Daniel posted how to unit test a CmdLet by calling invoke().GetEnumerator() then moving next. And Scott posted about testing powershell scripts with NUnit. And this article on msdn2 talks how to make a console app to run a command.
This example will be following very close to the msdn2 article to build PSCmdLet tests in NUnit. The PSCmdLet “Remove-Brain” is very simple, when invoked it does a WriteObject(true). The below fixture is just a sample of what can be done for unit testing with commandlets.
8 [TestFixture]
9 public class SampleTest
10 {
11 private static RunspaceConfiguration config;
12 private static Runspace runspace;
13 private static Pipeline pipe;
14 private static Command command;
- The FixtureSetup creates a RunspaceConfiguration which loads the snapin
- The FixtureSetup creates a runspace and opens it
16 [TestFixtureSetUp]
17 public void FixtureSetup()
18 {
19 config = RunspaceConfiguration.Create();
20 PSSnapInException warning;
21 config.AddPSSnapIn("LuifITPSSnapin", out warning);
22
23 runspace = RunspaceFactory.CreateRunspace(config);
24 runspace.Open();
25 }
27 [TestFixtureTearDown]
28 public void FixtureTearDown()
29 {
30 runspace.Close();
31 }
- The Setup creates a new pipeline and adds the “Romove-Brain” command
33 [SetUp]
34 public void Setup()
35 {
36 pipe = runspace.CreatePipeline();
37 command = new Command("Remove-Brain");
38 pipe.Commands.Add(command);
39 }
- The test adds the parameter to the command
- The pipeline is invoked which runs the command
- The returned collection of PSObjects contains the objects that where written.
- Asserting that there is only one and that my brain has been removed
41 [Test]
42 public void CanRemoveMyBrain()
43 {
44 command.Parameters.Add(new CommandParameter("Person", "ME"));
45
46 Collection<PSObject> psObject = pipe.Invoke();
47
48 Assert.AreEqual(1, psObject.Count);
49 Assert.IsTrue((bool) psObject[0].BaseObject);
50 }
51 }