Question

So I know with TDD you're supposed to write tests first but I can't get my head around how to write a test for the following code. Can someone help me out with at starting point?

private string GetWMIProperty(string property)
{
    string value = string.Empty;
    SelectQuery selectQuery = new SelectQuery("Win32_OperatingSystem");
    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery))
    {

        foreach (ManagementObject mo in searcher.Get())
        {
             value = mo[property].ToString();
        }
    }
    return value;
}
Was it helpful?

Solution

You'd just write tests for the method's various outcomes, and in doing so you'd define the method's expected behaviour without actually writing the method yet:

[TestMethod]
public MyClass_GetWMIProperty_GivenGoodInput_ReturnsString()
{
    var myClass = new MyClass();
    var result = myClass.GetWMIProperty("goodinput");
    Assert.IsNotNull(result);
}

[TestMethod]
public MyClass_GetWMIProperty_GivenNullInput_ThrowsArgumentNullException()
{
    var myClass = new MyClass();

    try
    {
        var result = myClass.GetWMIProperty(null);
    }
    catch (ArgumentNullException)
    {
        // Good
        return;
    }

    // Exception not thrown
    Assert.Fail();
}

[TestMethod]
public MyClass_GetWMIProperty_GivenBadInput_ReturnsNull()
{
    var myClass = new MyClass();
    var result = myClass.GetWMIProperty("badinput");
    Assert.IsNull(result);
}

Your method would be stubbed as follows:

// Note public/internal so tests can see it
public string GetWMIProperty(string property)
{
    // Stubbed
    throw new NotImplementedException();
}

These 3 test methods will fail in this state, because NotImplementedException will be thrown and not caught by any of them.

Next you'd write the actual meat of the method so that you can call it in these tests and they'd all pass. The core idea of TDD is that the tests define the behaviour. Here we have defined:

  • good input returns a string
  • bad input returns null
  • null input throws an ArgumentNullException.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top