Migrating from a health check to a behavioral check using MOQ

I am trying to cover TDD and have begun to study mockery. I need advice on what I should test and how to make my classes more behavioral rather than just 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 checking the status check will be

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

I'm not quite sure what I should do to check the behavior, can someone provide some samples using Moq?

+6
moq mocking
source share
2 answers

You will have to change your Post class a bit, but don't worry.

 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 small redesign will give you the opportunity to use Moq to test the behavior you expect. I will also show you a slightly better way to name your tests so that they understand 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 it's all. Mock automatically throws an exception if all expectations fail.

Hope this helps.

-Anderson

+5
source share

I can't remember the moq syntax, but I see it like that.

Make a comment on the IComments interface and state that this call is invoked on the interface.

0
source share

All Articles