3

Using Microsoft Visual Studio 2017's built in test with Moq.

I have a simple class that creates some content, then sends the content to a notification system. I need to test if the notification system was called, but that the call included some text.

 public void DoStuff()
            var tenantSettings = _tenantService.GetTenantSettings();
            tenantSettings.Body = "xxx SOME VALUE xxx";
            MyService.SendMail(tenantSettings.Body);

How can I test that SendMail contains the text "SOME VALUE"?

I have a MOCK setup:

 MyServiceMock.Setup(x=>x.SendMail(It.IsAny<string>);
Ian Vink
  • 66,960
  • 104
  • 341
  • 555

2 Answers2

7

You can simply use Verify method on your mock:

MyServiceMock.Verify(x => x.SendMail("SOME VALUE"), Times.Once());

Edit:

If you want to verify whether the text passed as a parameter does not matches exactly, but just contains the tested value, you can use, as Scott Chamberlain wrote:

MyServiceMock.Verify(x => x.SendMail(It.Is<string>(s => s.Contains("SOME VALUE")), Times.Once());
Community
  • 1
  • 1
tdragon
  • 3,209
  • 1
  • 16
  • 17
2

You need to use the Verify function allong with the It.Is<TValue>(Func<TValue,bool>) function to search for the substring.

MyServiceMock.Verify(x => x.SendMail(It.Is<string>(s => s.Contains("SOME VALUE")), Times.Once());

You put this line at the end of your test function after DoStuff() has been called.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431