SHARE
TWEET

Xml Moq

a guest Jan 24th, 2020 70 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 = 50;
  23.             var expected = Guid.Empty.ToString();
  24.  
  25.  
  26.             //Act
  27.             var actual = myService.GetXml(id);
  28.  
  29.             //Assert
  30.             Assert.AreEqual(expected, actual.FirstChild.InnerText);
  31.         }
  32.     }
  33.  
  34.     public class MyService : IMyService
  35.     {
  36.         public XmlDocument GetXml(int id)
  37.         {
  38.             //Do real stuff
  39.             return new XmlDocument();
  40.         }
  41.     }
  42.  
  43.     public interface IMyService
  44.     {
  45.         XmlDocument GetXml(int id);
  46.     }
  47.  
  48.     public class MockSetup
  49.     {
  50.         public Mock<IMyService> MyService { get; set; }
  51.  
  52.         public MockSetup()
  53.         {
  54.             MyService = new Mock<IMyService>();
  55.         }
  56.         public static MockSetup HappySetup()
  57.         {
  58.             var mockSetup = new MockSetup();
  59.  
  60.             var mockDoc = CreateMockDoc();
  61.  
  62.             mockSetup.MyService.Setup(m => m.GetXml(It.IsAny<int>())).Returns(mockDoc);
  63.             return mockSetup;
  64.         }
  65.  
  66.         private static XmlDocument CreateMockDoc()
  67.         {
  68.             XmlDocument mockDoc = new XmlDocument();
  69.             XmlElement el = (XmlElement)mockDoc.AppendChild(mockDoc.CreateElement("Main"));
  70.  
  71.             el.AppendChild(mockDoc.CreateElement("MyGuid")).InnerText = It.IsAny<Guid>().ToString();
  72.             return mockDoc;
  73.         }
  74.     }
  75. }
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