使用MOQ从状态验证到行为验证

6 moq mocking

我试图接受TDD并开始学习嘲笑.我需要一些关于我应该测试什么以及如何使我的类更具行为性而不是简单数据容器(带有一堆getter/setter)的建议.

考虑这个课程.

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

   public void AddComment(string message)
   {
      Comment.Add(new Comment(message));
   } 
}
Run Code Online (Sandbox Code Playgroud)

状态验证测试的一个例子是

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

我不确定我应该为行为验证做些什么,有人可以使用Moq提供一些样本吗?

And*_*mes 5

你必须稍微重新设计你的Post类,但不用担心.

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

     public void AddComment(string message)
     {
          _comments.Add(new Comment(message));
     }
}
Run Code Online (Sandbox Code Playgroud)

这种轻微的重新设计将使您能够使用Moq来验证您期望的行为.我还会向您展示一种更好的方法来命名您的测试,以便明确他们试图测试的内容.

[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();
}
Run Code Online (Sandbox Code Playgroud)

这就是全部.如果没有正确满足所有期望,Mock将自动抛出异常.

希望这可以帮助.

-Anderson