AutoMockContainer 支持具有非接口依赖项的自动模拟类
我有一个具有非接口依赖性的构造函数:
public MainWindowViewModel(IWorkItemProvider workItemProvider, WeekNavigatorViewModel weekNavigator)
我正在使用 Moq.Contrib automockcontainer。如果我尝试自动模拟 MainWindowViewModel 类,则会由于 WeekNavigatorViewModel 依赖项而收到错误。
是否有支持模拟非接口类型的自动模拟容器?
正如 Mark 所示;是的,你可以! :-) 我用 Mark 在他的答案中提供的内容替换了 Moq.Contrib AutoMockContainer,唯一的区别是自动生成的模拟被注册为单例,但您可以将其配置为可配置。这是最终的解决方案:
/// <summary>
/// Auto-mocking factory that can create an instance of the
/// class under test and automatically inject mocks for all its dependencies.
/// </summary>
/// <remarks>
/// Mocks interface and class dependencies
/// </remarks>
public class AutoMockContainer
{
readonly IContainer _container;
public AutoMockContainer(MockFactory factory)
{
var builder = new ContainerBuilder();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
builder.RegisterSource(new MoqRegistrationSource(factory));
_container = builder.Build();
}
/// <summary>
/// Gets or creates a mock for the given type, with
/// the default behavior specified by the factory.
/// </summary>
public Mock<T> GetMock<T>() where T : class
{
return (_container.Resolve<T>() as IMocked<T>).Mock;
}
/// <summary>
/// Creates an instance of a class under test,
/// injecting all necessary dependencies as mocks.
/// </summary>
/// <typeparam name="T">Requested object type.</typeparam>
public T Create<T>() where T : class
{
return _container.Resolve<T>();
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
/// <summary>
/// Registers and resolves the given service on the container.
/// </summary>
/// <typeparam name="TService">Service</typeparam>
/// <typeparam name="TImplementation">The implementation of the service.</typeparam>
public void Register<TService, TImplementation>()
{
var builder = new ContainerBuilder();
builder.RegisterType<TImplementation>().As<TService>().SingleInstance();
builder.Update(_container);
}
/// <summary>
/// Registers the given service instance on the container.
/// </summary>
/// <typeparam name="TService">Service type.</typeparam>
/// <param name="instance">Service instance.</param>
public void Register<TService>(TService instance)
{
var builder = new ContainerBuilder();
if (instance.GetType().IsClass)
builder.RegisterInstance(instance as object).As<TService>();
else
builder.Register(c => instance).As<TService>();
builder.Update(_container);
}
class MoqRegistrationSource : IRegistrationSource
{
private readonly MockFactory _factory;
private readonly MethodInfo _createMethod;
public MoqRegistrationSource(MockFactory factory)
{
_factory = factory;
_createMethod = factory.GetType().GetMethod("Create", new Type[] { });
}
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var swt = service as IServiceWithType;
if (swt == null)
{
yield break;
}
if (!swt.ServiceType.IsInterface)
yield break;
var existingReg = registrationAccessor(service);
if (existingReg.Any())
{
yield break;
}
var reg = RegistrationBuilder.ForDelegate((c, p) =>
{
var createMethod = _createMethod.MakeGenericMethod(swt.ServiceType);
return ((Mock)createMethod.Invoke(_factory, null)).Object;
}).As(swt.ServiceType).SingleInstance().CreateRegistration();
yield return reg;
}
public bool IsAdapterForIndividualComponents
{
get { return false; }
}
}
}
I have a constructor which has a non-interface dependency:
public MainWindowViewModel(IWorkItemProvider workItemProvider, WeekNavigatorViewModel weekNavigator)
I am using the Moq.Contrib automockcontainer. If I try to automock the MainWindowViewModel class, I get an error due to the WeekNavigatorViewModel dependency.
Are there any automocking containers which supports mocking of non-interface types?
As Mark has shown below; yes you can! :-) I replaced the Moq.Contrib AutoMockContainer with the stuff Mark presents in his answer, the only difference is that the auto-generated mocks are registered as singletons, but you can make this configurable. Here is the final solution:
/// <summary>
/// Auto-mocking factory that can create an instance of the
/// class under test and automatically inject mocks for all its dependencies.
/// </summary>
/// <remarks>
/// Mocks interface and class dependencies
/// </remarks>
public class AutoMockContainer
{
readonly IContainer _container;
public AutoMockContainer(MockFactory factory)
{
var builder = new ContainerBuilder();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
builder.RegisterSource(new MoqRegistrationSource(factory));
_container = builder.Build();
}
/// <summary>
/// Gets or creates a mock for the given type, with
/// the default behavior specified by the factory.
/// </summary>
public Mock<T> GetMock<T>() where T : class
{
return (_container.Resolve<T>() as IMocked<T>).Mock;
}
/// <summary>
/// Creates an instance of a class under test,
/// injecting all necessary dependencies as mocks.
/// </summary>
/// <typeparam name="T">Requested object type.</typeparam>
public T Create<T>() where T : class
{
return _container.Resolve<T>();
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
/// <summary>
/// Registers and resolves the given service on the container.
/// </summary>
/// <typeparam name="TService">Service</typeparam>
/// <typeparam name="TImplementation">The implementation of the service.</typeparam>
public void Register<TService, TImplementation>()
{
var builder = new ContainerBuilder();
builder.RegisterType<TImplementation>().As<TService>().SingleInstance();
builder.Update(_container);
}
/// <summary>
/// Registers the given service instance on the container.
/// </summary>
/// <typeparam name="TService">Service type.</typeparam>
/// <param name="instance">Service instance.</param>
public void Register<TService>(TService instance)
{
var builder = new ContainerBuilder();
if (instance.GetType().IsClass)
builder.RegisterInstance(instance as object).As<TService>();
else
builder.Register(c => instance).As<TService>();
builder.Update(_container);
}
class MoqRegistrationSource : IRegistrationSource
{
private readonly MockFactory _factory;
private readonly MethodInfo _createMethod;
public MoqRegistrationSource(MockFactory factory)
{
_factory = factory;
_createMethod = factory.GetType().GetMethod("Create", new Type[] { });
}
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var swt = service as IServiceWithType;
if (swt == null)
{
yield break;
}
if (!swt.ServiceType.IsInterface)
yield break;
var existingReg = registrationAccessor(service);
if (existingReg.Any())
{
yield break;
}
var reg = RegistrationBuilder.ForDelegate((c, p) =>
{
var createMethod = _createMethod.MakeGenericMethod(swt.ServiceType);
return ((Mock)createMethod.Invoke(_factory, null)).Object;
}).As(swt.ServiceType).SingleInstance().CreateRegistration();
yield return reg;
}
public bool IsAdapterForIndividualComponents
{
get { return false; }
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您利用支持即时解析所请求类型的DI 容器,您可以非常轻松地自己编写一个容器。
我最近使用 Autofac 和 Moq 编写了一个原型,但也可以使用其他容器反而。
这是适当的 IRegistrationSource:
您现在可以在单元测试中设置容器,如下所示:
这就是您开始所需的全部内容。
MyClass 是一个具有抽象依赖关系的具体类。以下是构造函数签名:
请注意,您不必在生产代码中使用 Autofac(或任何其他 DI 容器)。
You can pretty easily write one yourself if you leverage a DI Container that supports just-in-time resolution of requested types.
I recently wrote a prototype for exactly that purpose using Autofac and Moq, but other containers could be used instead.
Here's the appropriate IRegistrationSource:
You can now set up the container in a unit test like this:
That's all you need to get started.
MyClass is a concrete class with an abstract dependency. Here is the constructor signature:
Notice that you don't have to use Autofac (or any other DI Container) in your production code.