Created
July 19, 2012 10:39
-
-
Save slovely/3142945 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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