1

嗨,我很难模拟 IUnityContainer ,特别是我试图查看是否调用了 Register Type。这是我要测试的方法:

    private readonly IUnityContainer _container;

    public InjectorContainer(IUnityContainer container)
    {
        _container = container;
    }

    public void RegisterType(InjectorServiceModel dependencyService)
    {
        _container.RegisterType(dependencyService.From, dependencyService.To);
    }

这是我的 Unity 测试类:

 private Mock<IUnityContainer> _unitContaineMock;
    private InjectorContainer _injectorContainer;

    [TestInitialize]
    public void Initializer()
    {
        _unitContaineMock = new Mock<IUnityContainer>();
        _injectorContainer = new InjectorContainer(_unitContaineMock.Object);
    }

    [TestMethod]
    public void RegisterType_CheckIfContainerRegisterTypeIsCalled_Oance()
    {
        //Arrange
        var injectorServiceModel = new InjectorServiceModel()
        {
            From = typeof(IInjectorContainerFake),
            To = typeof(InjectorContainerFake)
        };
        bool wasCalled = false;
        _unitContaineMock.Setup(x => x.RegisterType(It.IsAny<Type>(), It.IsAny<Type>())).Callback(() =>
        {
            wasCalled = true;
        });
        //Act
        _injectorContainer.RegisterType(injectorServiceModel);

        //Assert
        Assert.IsTrue(wasCalled);
    }

这种状态下的代码实际上是我的第二次尝试,我第一次尝试这样做:

 [TestMethod]
    public void RegisterType_CheckIfContainerRegisterTypeIsCalled_Oance()
    {
        //Arrange
        var injectorServiceModel = new InjectorServiceModel()
        {
            From = typeof(IInjectorContainerFake),
            To = typeof(InjectorContainerFake)
        };
        //Act
        _injectorContainer.RegisterType(injectorServiceModel);

        //Assert
        _unitContaineMock.Verify(x => x.RegisterType(It.IsAny<Type>(), It.IsAny<Type>()), Times.Once);

    }

在这两种情况下,我都会收到带有以下消息的 SystemNotSuported 异常:

对非虚拟(在 VB 中可覆盖)成员的无效验证:x => x.RegisterType(It.IsAny(), It.IsAny(), new[] { })

据我所知,似乎当它试图验证时,它正在寻找一个带有 3 个参数的 RegisterType。

有谁知道我在这里做错了什么?

我正在尝试测试是否调用了 RegisterType。

4

1 回答 1

3

我 99% 确定你得到这个的原因是因为RegisterType你调用的重载实际上是在其他地方定义的扩展方法,你不能在扩展方法上使用设置/验证(因为它们在技术上是静态的)。我基于这里的方法列表:http IUnityContainer: //msdn.microsoft.com/en-us/library/microsoft.practices.unity.iunitycontainer_members (v=pandp.30).aspx 。接口上唯一RegisterType实际定义的就是这个,正如您所见,它需要五个参数。

可能的解决方案:

  1. 改用带有五个参数的重载。您将能够对此进行验证。但是,为了编写单元测试而使代码更复杂当然是相当愚蠢的。
  2. Use a "real" container instead of a mock, and instead of doing a Verify, call one of the IsRegistered overloads in your unit test to check if the type has actually been added to the container. This might be a preferable approach anyway. It will certainly be less brittle. Your unit test shouldn't really care which particular method was used to add the types to the container; it should just verify that the types have been added.
于 2013-09-07T13:24:53.607 回答