Search code examples
c#unit-testing

TestCleanup() Implementation


How would I write the [TestCleanup()] method for these [TestMethod()]'s.

I have 11 of the following:

When run individually they pass, when not run at the same time the first passes

[TestMethod()]
public void SplitTdsNameTest_SimpleValidName2()
{
    string tdsName = "Title FirstName MiddleName Surname";
    MemberName expected = new MemberName("Title", "FirstName MiddleName", "Surname");
    MemberName actual;
    actual = TdsTransformer.SplitTdsName(tdsName);
    Assert.AreEqual(expected, actual);
}


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

MemberName:

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

Splitter:

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

Solution

  • Based on what's provided, it doesn't look like any cleanup is necessary.

    If there's a TestInitialize method, just undo what's done there.

    If TdsTransformer.SplitTdsName stores any internal state, you'll have to clear that as well. Though if it does, it likely shouldn't be a static method.

    Based on the edits, these two methods worry me:

        SetAllowedTitles();
        SetTitles();
    

    They imply there is internal state which, in my opinion, is very bad for a static class. This is likely the issue you are seeing with consecutive tests not passing.

    To correct these and keep it static, have them return values instead of storing in static members:

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