我如何为这样的东西编写单元测试?

Gab*_*l W 0 c# tdd

所以我知道TDD你应该首先编写测试但我无法理解如何为下面的代码编写测试.有人可以在起点帮助我吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ney 6

您只需为方法的各种结果编写测试,并且这样做就可以定义方法的预期行为,而无需实际编写方法:

[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);
}
Run Code Online (Sandbox Code Playgroud)

您的方法将如下所示:

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

这三种测试方法在这种状态下都会失败,因为它们NotImplementedException会抛出并且不被其中任何一种捕获.

接下来,您将编写该方法的实际内容,以便您可以在这些测试中调用它们并且它们都会通过.TDD的核心思想是测试定义行为.我们在这里定义:

  • 好的输入返回一个字符串
  • 错误的输入返回null
  • null输入抛出ArgumentNullException.

  • 一些样式注释:有一个测试类用于在一个特定类中使用方法作为起始点的测试.这意味着你调用这个文件`MyClassTests`并从你的方法名中删除`MyClass`.此外:我认为这可能只是因为它是抽象的,但"错误输入"不是描述性的,应该是`_UnknownProperty_`和`_UnsupportedProperty_`(例如). (2认同)