0

我有以下测试:

[Test]
public void VerifyThat_WhenInitializingTheLoggingInterceptionFacility_TheLoggingInterceptorIsAdded()
{
    var kernel = new Mock<IKernel>(MockBehavior.Loose)
            {
                DefaultValue = DefaultValue.Mock
            };
    kernel.Setup(k => k.AddFacility<LoggingInterceptionFacility>())
                .Returns(kernel.Object)
                .Callback(() => ((IFacility)new LoggingInterceptionFacility()).Init(kernel.Object, Mock.Of<IConfiguration>()));

    kernel.Setup(k => k.Register(It.IsAny<IRegistration[]>()))
                  .Returns(kernel.Object)
                  .Verifiable();

    kernel.Object.AddFacility<LoggingInterceptionFacility>();

    kernel.Verify(k => k.Register(It.Is<IRegistration[]>(r => r.Contains(Component.For<LoggingInterceptor>()))));
}

如您所见,我通过调用设施的Init(IKernel, IConfiguration)方法来模拟内核的真实行为,该方法又调用受保护的Init()方法。
下面是受保护的 Init() 的样子:

protected override void Init()
{
    Kernel.ProxyFactory.AddInterceptorSelector(new LoggingModelInterceptorsSelector());
    Kernel.Register(Component.For<LoggingInterceptor>());
}

我预计验证会通过,但事实并非如此。如果我验证通过测试完全调用了 Kernel.Register It.IsAny<LoggingInterceptor>()
我在这里不匹配什么?有没有办法让这个测试通过?

4

1 回答 1

3

看来您在这里测试太多了。AddFacility您通过管道调用从到有效地重新实现了温莎的许多内部结构LoggingInterceptionFacility.Init

真正需要测试的只是您的设施调用Register内核并假设 Windsor 做了正确的事情。毕竟,它有自己的单元测试;)

这样做之后,测试变得更具可读性,我认为这是最重要的方面。

[Test]
public void VerifyThat_WhenInitializingTheLoggingInterceptionFacility_TheLoggingInterceptorIsAdded()
{
    var kernel = new Mock<IKernel>();

    kernel.Setup(k => k.Register(It.IsAny<IRegistration[]>()))
                  .Returns(kernel.Object)
                  .Verifiable();
    //Explicit interface implementation requires casting to the interface
    ((IFacility)new LoggingInterceptionFacility()).Init(kernel.Object, Mock.Of<IConfiguration>().Object);
    //verify the type of registration here
    kernel.Verify(k => k.Register(It.Is<IRegistration[]>(r => r[0] is ComponentRegistration<LoggingInterceptor>);
}

EDIT调用以Component.For在设置和执行之间返回不同的实例。我更新了代码以反映这一点,并让验证检查组件的类型。

于 2011-05-18T06:21:41.310 回答