Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 277
Kris Avatar asked Jan 29 '16 15:01

Kris


1 Answers

You already have an instance of object IFoo fooMock, so you need to register using RegisterInstance method:

container.RegisterInstance<IFoo>(fooMock.Object);
like image 97
Backs Avatar answered Nov 14 '22 22:11

Backs