Skip to content

Instantly share code, notes, and snippets.

@slovely
Created July 19, 2012 10:39
Show Gist options
  • Save slovely/3142945 to your computer and use it in GitHub Desktop.
Save slovely/3142945 to your computer and use it in GitHub Desktop.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace ConsoleApplication1
{
[TestClass]
public class CustomMoq
{
public class Message
{
public string Body { get; set; }
}
public interface IEmailer
{
void Send(Message msg);
}
public class ThingBeingTested
{
private readonly IEmailer _emailer;
public ThingBeingTested(IEmailer emailer)
{
_emailer = emailer;
}
public void Method()
{
var msg = new Message();
msg.Body = "The test message";
_emailer.Send(msg);
}
}
//***Instead of this...
[TestMethod]
public void Test()
{
var mock = new Mock<IEmailer>();
mock.Setup(x => x.Send(It.IsAny<Message>()))
.Callback<Message>(msg =>
{
Assert.IsTrue(msg.Body.Contains("test"));
});
var sut = new ThingBeingTested(mock.Object);
sut.Method();
}
//***Do this...
[TestMethod]
public void Test2()
{
var mock = new Mock<IEmailer>();
mock.Setup(x => x.Send(BodyContains("test")))
.Verifiable("Expected the email to contain 'test'.");
var sut = new ThingBeingTested(mock.Object);
sut.Method();
mock.VerifyAll();
}
public Message BodyContains(string expectedText)
{
return Match.Create<Message>(x => x.Body.Contains(expectedText));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment