What is the best method for testing serialization?

using System; using System.Xml.Serialization; using System.IO; namespace Mailer { public class ClientConfiguration { public virtual bool Save(string fileName) { XmlSerializer serializer = new XmlSerializer(typeof(ClientConfiguration)); using (StreamWriter writer = new StreamWriter(fileName)) { serializer.Serialize(writer, this); } return true; } } } 

In the above code, I would like to stub / exhaust the serializer.Serialize method to ensure that the method is called. I tried so much with moq and NMock but could not.

Please help me drown / ridicule the calls to the serializer.

+6
source share
1 answer

If you are not using Typemock Isolator or Moles, you cannot replace anything internal created using the new keyword.

You need to first extract the interface from the XmlSerializer and then insert it into the class.

As an example, you can enter this interface:

 public interface IXmlSerializer { public void Serialize(Stream stream, object o); } 

Add this to your Mailer class as follows:

 public class ClientConfiguration { private readonly IXmlSerializer serializer; public ClientConfiguration(IXmlSerializer serializer) { if (serializer == null) { throw new ArgumentNullException("serializer"); } this.serializer = serializer; } public virtual bool Save(string fileName) { using (StreamWriter writer = new StreamWriter(fileName)) { this.serializer.Serialize(writer, this); } return true; } } 

Now you can enter mock into the class:

 var mock = new Mock<IXmlSerializer>(); var sut = new ClientConfiguration(mock.Object); 

The above example uses Moq.

+8
source

Source: https://habr.com/ru/post/886519/


All Articles