简体   繁体   中英

MS Fakes, passing parameter into constructor

I have the following concrete class

public class Service
{
    private IRepository _rep;

    public Service(IRepository rep)
    {
        _rep() = rep;
    }

    public Boolean Foo(Int32 param1)
    {
        _rep.Foo(param1);
    }

    public void Bar()
    {
        _rep.Bar();
    }
}

I have created the following shim for it.

    using (ShimsContext.Create())
    {
        ShimService shimService = new ShimService()
        {
            FooInt32 = (param1) => { return true; },
        };
    }

I want foo to always return true. This works.

I want Bar to operate normally. This doesn't work.

When I debug _rep is null so I believe I need to pass this an IRepository into the Shims constructor but I can't work out how to do it.

I found the solution. You have to create an instance of the Service you want to Shim which includes the injection of IRepository and pass that that service into the Shim.....so

            IRepository rep = new Repository();
            Service service = new Service(rep);
            ShimSignOffService shimService = new ShimSignOffService(service)
            {
                IsBookmarkProcessedInt32 = (bookmarkId) => { return true; },

            };

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