简体   繁体   English

模拟接口的多个实例:最后一个模拟的设置会影响其他模拟

[英]Mocking multiple instances of interface: Setup of the last mock affects the others

Following my question about conditional-dependency-resolver-on-run-time 以下是我关于运行时条件依赖解析器的问题

I built a BooService that has a injected array of IFooService[] , And a FooFactory method that return one of the foo services based on a given key on run time. 我构建了一个BooService ,它具有IFooService[]的注入数组,以及一个FooFactory方法,该方法根据运行时的给定键返回一个foo服务。

class BooService
{
    readonly IFooService[] _fooServices;

    BooService(IFooService[] services)
    {
        this._fooServices = services;
    }
    IFooService FooFactory(Guid id)
    {
        IFooService fooService = Array.Find(this._fooServices, 
                                     service => service.Id == id);
        return fooService;
    }
}

public class FooService1 : IFooService
{
    public int Id { get { return 1; }  
}
public class FooService2 : IFooService
{
    public int Id { get { return 2; }  
}

Everything works OK on run-time but my UnitTests fails: 在运行时一切正常,但我的UnitTests失败:

AutoMock _mock = Autofac.Extras.Moq.AutoMock.GetLoose();
Mock<IFooService> fooService1 = _mock.Mock<IFooService>();
fooService1
    .Setup(x => x.Id)
    .Returns(1);

Mock<IFooService> fooService2 = _mock.Mock<IFooService>();
fooService2
    .Setup(x => x.Id)
    .Returns(2);

IFooService[] fooServices = new IFooService[] { fooService1.Object, fooService2.Object };

BooService booService = new BooService(fooServices);
booService.FooFactory(1); //Result in null
booService.FooFactory(2); //Result in "fooService2"

For the id of 1 the line code of Array.Find(this._fooServices, ...); 对于ID为1的行代码,为Array.Find(this._fooServices, ...); result in null ! 结果为null

When I comment the creation of the second instance of the mocked interface the code of booService.FooFactory(1); 当我评论booService.FooFactory(1);接口的第二个实例的创建时, booService.FooFactory(1); result in fooService1 . 结果为fooService1 So I guessing the second Setup affects somehow on the first instance. 因此,我猜想第二个Setup会以某种方式影响第一个实例。

Any suggestion why when creating two mocked instance of the interface makes the Array.Find(...) find only last created mocked instance ? 有什么建议为什么在创建接口的两个Array.Find(...)实例时使Array.Find(...) 仅查找最后创建Array.Find(...) 实例

If it is a bug in Moq : any clean work around to unit test the find process? 如果这是Moq的错误:是否有任何清洁方法可以对测试过程进行单元测试?

_mock.Mock<IFooService>()

Will return the same mocked instance for each call so the setup is actually being done on one instance. 每次调用都会返回相同的模拟实例,因此实际上是在一个实例上完成设置。 Last setup wins every time. 最后的设置每次都会获胜。

Here is the manual approach 这是手动方法

IFooService fooService1 = Mock.Of<IFooService>(_ => _.Id == 1);
IFooService fooService2 = Mock.Of<IFooService>(_ => _.Id == 2);

IFooService[] fooServices = new IFooService[] { fooService1.Object, fooService2.Object };

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

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