How to mock ISerializable classes with Moq?

System.Reflection.Assembly is abstract, so you can't create a new instance of it. However, you could create a test class which does and Mock that.

Example:

[TestMethod]
public void TestSomethingThatNeedsAMockAssembly()
{
    string title = "title";
var mockAssembly = new Mock();
mockAssembly.Setup(a => a.GetCustomAttributes(It.Is(s => s == Type.GetType("System.Reflection.AssemblyTitleAttribute")), It.IsAny())).Returns(new System.Attribute[] { new AssemblyTitleAttribute(title) } );

var c = new ClassThatTakesAssemblyAndParsesIt(mockAssembly.Object); Assert.IsTrue(c.AssemblyTitle == title); //etc } public class TestAssembly : Assembly { public TestAssembly() { //could probably do something interesting here } }


The issue is not with ISerializable interface. You can mock ISerializable classes.

Notice the exception message:

The type System.Reflection.Assembly implements ISerializable, but failed to provide a deserialization constructor

Problem is, that Assembly does not provide deserialization constructor.


As explained already, the problem is Assembly not exposing a deserialization constructor. This does not mean it can't be done though.

A solution using Moq as per your example would be:

    var mock = new Mock<_Assembly>();
    result.Setup(/* do whatever here as usual*/);

Note that to use _Assembly you will need to reference System.Runtime.InteropServices