繁体   English   中英

将Moq模拟对象注册为Unity容器的类型

[英]Register a Moq mock object as type for a Unity container

由于我的sut类有一个带有IUnityContainer作为参数的构造函数,我喜欢在我的单元测试中设置一个新的Unity容器并将其传递给sut。 我喜欢在这里使用Moq,因为我还必须非常适合某些方法调用。 我在这里尝试的是

public interface IFoo
    {
        void Bar();
    }

    class Program
    {
        static void Main(string[] args)
        {
            var fooMock = new Mock<IFoo>();

            fooMock.Setup(x => x.Bar()).Callback(() => Console.WriteLine("Hello"));

            IUnityContainer container = new UnityContainer();
            container.RegisterType(typeof (IFoo), fooMock.Object.GetType());

            var sut = container.Resolve<IFoo>();
            sut.Bar();

            Console.Read();
        }
    }

但这会导致ResulutionFailedException 任何想法我能做什么或可能替代这个问题?

您已经有一个对象IFoo fooMock的实例,因此您需要使用RegisterInstance方法进行注册

container.RegisterInstance<IFoo>(fooMock.Object);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM