locked
Trouble Stubbing UnityContainer using Microsoft Fakes RRS feed

  • Question

  • Greetings,

    I'm posting this for one of our programmers that has no access to the internet.

    "

    I am having trouble stubbing my UnityContainer using Microsoft Fakes . I have three service classes that need to be resolved 
    and I can't figure out how to stub out the Resolve<> method with multiple objects.
    Here is my test initialization code.

                _container = new StubIUnityContainer();

                _container.ResolveTypeStringResolverOverrideArray = (type, s, arg3) => _exceptionHandler;
                _container.ResolveTypeStringResolverOverrideArray = (type, s, arg3) => _unitOfWork;
                _container.ResolveTypeStringResolverOverrideArray = (type, s, arg3) => _messageBoxService;

                _service = new ActiveToolsBySelectedLocationService(_container);

    This is the constructor for the ActiveToolsBySelectedLocationService.

            private readonly IAppExceptionHandler _exceptionHandler;
            private readonly IUnitOfWork _unitOfWork;
            private readonly IMessageBoxService _messageBoxService;

            public ActiveToolsBySelectedLocationService(IUnityContainer container)
            {
                _exceptionHandler = container.Resolve<IAppExceptionHandler>();
                _unitOfWork = container.Resolve<IUnitOfWork>();
                _messageBoxService = container.Resolve<IMessageBoxService>();
            }

    When the test initialize method runs I get the following exception on the first line of the contructor.

    "Unable to cast object of type 'UtilityLibrary.Interfaces.Fakes.StubIMessageBoxService' to type 'UtilityLibrary.Interfaces.IAppExceptionHandler'.""
    Wednesday, February 26, 2020 6:52 PM

All replies

  • Hi P Q,

    Welcome to MSDN forum.

    According to your description, you could refer this answer, to define an interface that includes your class which is in your test project, then use that in your mock.

    public interface ICanTestAAndB : IInterfaceA, IInterfaceB {}
    
    var mock = new Mock<ClassA<ICanTestAAndB>>();

    Hope it could help you.

    Best Regards,

    Dylan


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com

    Thursday, February 27, 2020 5:46 AM