I am trying to write a simple unittest in dotnetfiddle using Moq, but for some reason the runtime complains about security accessibility:
Run-time exception (line 20): The type initializer for 'Moq.ProxyFactory' threw an exception.
Stack Trace:
[System.TypeLoadException: Inheritance security rules violated while overriding member: 'Castle.DynamicProxy.ProxyGenerationOptions.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.] at Moq.CastleProxyFactory..ctor() at Moq.ProxyFactory..cctor()
[System.TypeInitializationException: The type initializer for 'Moq.ProxyFactory' threw an exception.] at Moq.ProxyFactory.get_Instance() at Moq.Guard.IsVisibleToProxyFactory(MethodInfo method) at Moq.InvocationShape..ctor(LambdaExpression expression, MethodInfo method, IReadOnlyList
1 arguments, Boolean exactGenericTypeArguments, Boolean skipMatcherInitialization, Boolean allowNonOverridable) at Moq.ExpressionExtensions.<Split>g__Split|5_0(Expression e, Expression& r, InvocationShape& p, Boolean assignment, Boolean allowNonOverridableLastProperty) at Moq.ExpressionExtensions.Split(LambdaExpression expression, Boolean allowNonOverridableLastProperty) at Moq.Mock.Setup(Mock mock, LambdaExpression expression, Condition condition) at Moq.Mock
1.Setup[TResult](Expression`1 expression) at Unittests.Run() :line 20 at Program.Main() :line 10
I searched some other dotnetfiddles that do almost the same (like this one), but do not throw the error. This seems dotnetfiddle specific, because in Visual Studio this works. Do I need to set some specific .NET security flags?
using System;
using Moq;
using AssertLibrary;
public class Program
{
public static void Main()
{
var unittest = new Unittests();
unittest.Run();
}
}
public class Unittests
{
public void Run()
{
// Arrange
var cacheMock = new Mock<ICache>();
cacheMock
.Setup(c => c.GetOrSet<MyModel>(It.IsAny<string>(), It.IsAny<Func<MyModel>>()))
.Returns((string key, Func<MyModel> captured) => { return captured(); });
var stuffs = new Stuffs(cacheMock.Object);
// Act
var result = stuffs.GetModel();
// Assert
Assert.Equals(5, result.MyProperty);
}
}
public class MyModel
{
public int MyProperty { get; set; }
}
public class Stuffs
{
private ICache _cache;
public Stuffs(ICache cache)
{
_cache = cache;
}
public MyModel GetModel()
{
var model = _cache.GetOrSet("cache-key", () =>
{
return new MyModel
{
MyProperty = 5
};
});
return model;
}
}
public interface ICache
{
T GetOrSet<T>(string key, Func<T> setter);
}
public class Cache : ICache
{
public T GetOrSet<T>(string key, Func<T> setter)
{
// do stuff
return setter();
}
}