TestCleanup()实现

时间:2011-11-02 15:20:20

标签: c# unit-testing

我如何为[TestMethod()]编写[TestCleanup()]方法。

我有以下11个:

当单独运行时,它们通过,而不是在第一次通过的同时运行

[TestMethod()]
public void SplitTdsNameTest_SimpleValidName2()
{
    string tdsName = "Mr Daniel George Trunley";
    MemberName expected = new MemberName("Mr", "Daniel George", "Trunley");
    MemberName actual;
    actual = TdsTransformer.SplitTdsName(tdsName);
    Assert.AreEqual(expected, actual);
}


[TestMethod()]
public void SplitTdsNameTest_SimpleValidName3()
{
    string tdsName = "Daniel George Trunley";
    MemberName expected = new MemberName("", "", "Daniel George Trunley");
    MemberName actual;
    actual = TdsTransformer.SplitTdsName(tdsName);
    Assert.AreEqual(expected, actual);
}

成员名称:

public struct MemberName
{
    public string Title;
    public string FirstNames;
    public string LastNames;

    public MemberName(string title, string firstNames, string lastNames)            
    {            
        Title = title;
        FirstNames = firstNames;
        LastNames = lastNames;
    }
}

SplitTds:

public MemberName SplitTdsName(string tdsName)
    {
        return NameSplitter.Splitter(tdsName);
    }

分配器:

public static MemberName Splitter(string fullName)
    {
        nameInFull = fullName;
        SetAllowedTitles();
        SplitNamesAndRemovePeriods();
        SetTitles();
        MemberName splitName = new MemberName(titles, firstNames, lastNames);
        return splitName;
    }

1 个答案:

答案 0 :(得分:4)

根据提供的内容,看起来不需要进行任何清理。

如果有TestInitialize方法,只需撤消在那里完成的操作。

如果TdsTransformer.SplitTdsName存储任何内部状态,您也必须清除它。虽然如果它 ,它可能不应该是静态方法。

根据编辑,这两种方法让我担心:

    SetAllowedTitles();
    SetTitles();

他们暗示存在内部状态,在我看来,对于静态类来说,非常糟糕。这可能是您在连续测试未通过时看到的问题。

要更正这些保持静态,请让它们返回值而不是存储在静态成员中:

    var allowedTitles = SetAllowedTitles(fullName);
    var names = SplitNamesAndRemovePeriods(fullName);  //likely a struct or class with first/last names
    var titles = SetTitles(allowedTitles);