SHARE
TWEET

Xml Moq Example

a guest Jan 24th, 2020 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Xml;
  3. using Moq;
  4. using NUnit.Framework;
  5.  
  6. namespace MockXmlTest
  7. {
  8.     [TestFixture]
  9.     public class MyServiceTests
  10.     {
  11.         private MockSetup _mockSetup;
  12.         [SetUp]
  13.         public void Init()
  14.         {
  15.             _mockSetup = MockSetup.HappySetup();
  16.         }
  17.         [Test]
  18.         public void MyService_Should_Return_Data()
  19.         {
  20.             //Arrange
  21.             var myService = _mockSetup.MyService.Object;
  22.             var id = 42;
  23.             var expected = Guid.Empty.ToString();
  24.  
  25.             //Act
  26.             var actual = myService.GetXml(id);
  27.  
  28.             //Assert
  29.             Assert.AreEqual(expected, actual.FirstChild.InnerText);
  30.         }
  31.     }
  32.  
  33.     public class MyService : IMyService
  34.     {
  35.         public XmlDocument GetXml(int id)
  36.         {
  37.             //Do real stuff
  38.             return new XmlDocument();
  39.         }
  40.     }
  41.  
  42.     public interface IMyService
  43.     {
  44.         XmlDocument GetXml(int id);
  45.     }
  46.  
  47.     public class MockSetup
  48.     {
  49.         public Mock<IMyService> MyService { get; set; }
  50.  
  51.         public MockSetup()
  52.         {
  53.             MyService = new Mock<IMyService>();
  54.         }
  55.         public static MockSetup HappySetup()
  56.         {
  57.             var mockSetup = new MockSetup();
  58.  
  59.             var mockDoc = CreateMockDoc();
  60.  
  61.             //Matches any id of an integer, returns a XmlDocument mock
  62.             mockSetup.MyService.Setup(m => m.GetXml(It.IsAny<int>())).Returns(mockDoc);
  63.             return mockSetup;
  64.         }
  65.  
  66.         private static XmlDocument CreateMockDoc()
  67.         {
  68.             //<Main><MyGuid>00000000-0000-0000-0000-000000000000</MyGuid></Main>
  69.             XmlDocument mockDoc = new XmlDocument();
  70.             XmlElement el = (XmlElement)mockDoc.AppendChild(mockDoc.CreateElement("Main"));
  71.  
  72.             el.AppendChild(mockDoc.CreateElement("MyGuid")).InnerText = It.IsAny<Guid>().ToString();
  73.             return mockDoc;
  74.         }
  75.     }
  76. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top