简体   繁体   中英

Register a Moq mock object as type for a Unity container

Since my sut class has a constructor with a IUnityContainer as parameter I like to setup a new Unity container im my unit test and pass it to the sut. I like to use Moq here because I also have to veryfy for certain method calls. What I've tried here is

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();
        }
    }

But this results in an ResulutionFailedException . Any ideas what I can do or what might be an alternative to this problem?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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