user284654
user284654

Reputation:

TDD with MS Test

Like all good programmers, I'm trying to get some things straight when using TDD with MS Test. I'm following the basic Arrange, Act, Assert pattern, and something looks too complicated for my Act code. I'm under the assumption that there should only be one action in the Act line. So, given my sample code below, am I getting off track by first performing one action and THEN testing its condition? Thanks for the input.

    [TestMethod]
    public void TheCountOfAllRecordsIsGreaterThanZero()
    {
        //Arrange
        var auditLog = new AuditMasterClass();

        //Act

        //Create a new record in a local list of objects
        auditLog.LogAction("MyPersonName", DateTime.Now, "Stuff", "MoreStuff",
                                   "Desc",
                                   "Comments", true, false,
                                   "UndoStatement");

        //Return the count of objects in the local list
        var count = auditLog.GetCommentCount();

        //Assert
        Assert.IsTrue(count > 0);
    }

Upvotes: 3

Views: 1826

Answers (3)

Dror Helper
Dror Helper

Reputation: 30780

The test seems fine to me - I wouldn't be too dogmatic here but if it makes you feel better you can mark the line: var count = auditLog.GetCommentCount(); as part of the assertion phase ;)

One thing I would change in the test is the actual assertion - use Assert.AreNotEqual(0, count) or Assert.IsTrue(count > 0, string.Format("Count was not greater than 0, it was {0}", count)) - this way you'll get a better error message in case the assertion fails.

Upvotes: 5

philant
philant

Reputation: 35806

Yes, there usually is only one action per test case. Invoking a getter can be considered as not being an action and thus, belonging to the Assert portion of the testcase.

In the TheCountOfAllRecordsIsGreaterThanZero test shown above, the creation of a new record is part of the Arrange section - or the test is misnamed and could be TheCountOfAllRecordsIncreasedUponLogAction.

I'd also like to point out that one action per test case could means several lines of code. The idea is not a write a whole scenario with a long sequence of actions.

Upvotes: 1

Carl Manaster
Carl Manaster

Reputation: 40326

I don't see any problem with what you've done. I would tend to inline the count variable and simply

Assert.IsTrue(auditLog.GetCommentCount() > 0);

but it's not significantly different. Your test, as written, says that you are expecting when LogAction() is called with a particular set of parameters, there will be one or more comments in the log. That's clear. One thing I like to do is to assert the contrary of my assertion before the action, so I know that the action is really what brought about the condition. That would, of course, be:

Assert.IsTrue(auditLog.GetCommentCount() == 0);

right before your Act.

Upvotes: 4

Related Questions