Going From State Verification to Behavioral Verification using MOQ

mockingmoq

I am trying to embrace TDD and started learning about mocking. I need some advice on what i should test and how to make my classes more behavioral and not simple data containers (with a bunch of getters/setters).

Consider this class.

public class Post
{
   List<Comment> Comments {get; private set;}

   public void AddComment(string message)
   {
      Comment.Add(new Comment(message));
   } 
}

An example of a state verification test would be

[Test]
public void CanAddCommentToPost()
{
  Post p = new Post();
  p.AddComment("AAAAA");
  Assert.AreEqual(1,  Comments.Count);
}

I', not exactly sure what i should be doing for behavioural verification, can someone provide some samples using Moq?

Best Solution

You'd have to redesign your Post class a bit, but no worries.

public class Post
{
     private IList<Comment> _comments;
     public Post(IList<Comment> commentContainer)
     {
          _comments = commentContainer;
     }

     public void AddComment(string message)
     {
          _comments.Add(new Comment(message));
     }
}

This slight redesign will give you the ability to use Moq to verify the behavior your are expecting. I'll also show you a slightly better way to name your tests so that it's clear what they are trying to test.

[Test]
public void AddComment_NonNullMessage_IsAddedToCollection
{
     string message = "Test message";

     //Setup expectations
     Mock<IList<Comment>> commentsMock = new Mock<IList<Comment>>();
     commentsMock.Setup(list => list.Add(new Comment(message)));

     //Create target, passing in mock list
     Post target = new Post(commentsMock.Object);
     target.AddComment(message);

     //Verify our expectations are met
     commentsMock.VerifyAll();
}

And that is all. The Mock will automatically throw an exception if all expectations are not met correctly.

Hope this helps.

-Anderson