Posted By

heathbo on 07/03/14


Tagged

c# Moq


Versions (?)

Using Moq, check to see the value of passed in parameters.


 / Published in: C#
 

Example 1: I'm verifying that the list that is passed in has 3 attachments. SendMail is run later in the SendEmail method.

Example 2: I'm verifying that the object that is passed into the method has the appropriate values.

  1. Example 1:
  2.  
  3. private MockRepository repository = new MockRepository(MockBehavior.Loose);
  4. private Mock<IEmailService> mockEmailService = repository.Create<IEmailService>();
  5. private EmailUtility target = new EmailUtility(mockEmailService.Object);
  6.  
  7.  
  8. // Setup
  9. const string emailAddress = @"[email protected]";
  10. const string messageSubject = @"foo example";
  11. const string messageBody = @"foo body";
  12. const bool highPriority = true;
  13. const string fromAccount = "TestAccount";
  14.  
  15. var attachmentList = new List<Attachment>();
  16.  
  17. attachmentList.Add(new Attachment(new StreamClass(), ""));
  18. attachmentList.Add(new Attachment(new StreamClass(), ""));
  19. attachmentList.Add(new Attachment(new StreamClass(), ""));
  20.  
  21. // Action
  22. target.SendEmail(emailAddress, messageSubject, messageBody, true, fromAccount, attachmentList);
  23.  
  24. // Assert
  25. mockEmailService.Verify(x => x.SendMail(It.Is<MailMessage>(p => p.Attachments.Count() == 3), It.IsAny<bool>()));
  26.  
  27. ------------------------------
  28.  
  29. Example 2:
  30.  
  31. private MockRepository mockRepository;
  32. private Mock<IProvider> mockProvider;
  33.  
  34. var exception = new BiProcessorException("Test Exception");
  35. var brokerInvoiceModel = new BrokerInvoiceModel(){BrokerInvoiceId = 123,
  36. BrokerInvoiceNumber = "BI456"};
  37.  
  38. mockProvider.Setup(h => h.BiProcessingErrorProvider.InsertBiProcessingError(
  39. It.Is<BiProcessingError>(x => x.BrokerInvoiceId == brokerInvoiceModel.BrokerInvoiceId
  40. && x.BrokerInvoiceNumber == brokerInvoiceModel.BrokerInvoiceNumber
  41. && x.ExceptionInfo == exception.Message
  42. && x.ExtendedInfo == exception.ToString()))).Verifiable();
  43.  
  44. // Action
  45. target.CreateErrorLog(exception, brokerInvoiceModel);
  46.  
  47. // Assert
  48. mockRepository.VerifyAll();

Report this snippet  

You need to login to post a comment.