开发者

Going From State Verification to Behavioral Verification using MOQ

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?


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


I cannot remember the moq syntax to hand but I see it like this.

Make Comments an a interface of IComments and assert that that Add is called on the interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜