2011-05-15 21 views
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>())))); 
} 

正如你看到的,我通过调用嘲讽内核的实际行为facilitiy的Init(IKernel, IConfiguration)方法,依次调用受保护的方法Init()
这里是保护的init()的样子:

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

我预期的验证会通过,但它没有。如果我通过It.IsAny<LoggingInterceptor>()确认Kernel.Register被调用,测试通过。
我在这里不匹配什么?有没有办法让这个测试通过?

回答

3

看来你在这里测试的方式太多了。通过管理从AddFacilityLoggingInterceptionFacility.Init的呼叫,您正在有效地重新布置很多Windsor的内部部件。

所有的你真的需要测试的事实是,你的设施在内核上调用Register并假定温莎做对了。毕竟,它有自己的单元测试;)

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

[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>); 
} 

编辑通话设置和执行之间Component.For返回不同的实例。我更新了代码以反映并验证组件的类型。

+0

你错了。首先你不能直接调用Init(IKernel,IConfiguration)。你必须投身于IFacility才能做到这一点。其次,我正在隔离温莎的行为。它是否正确写入并不重要,我自然而然地使用它,就像打算使用的用例一样。但是我不知道Component.For返回的对象没有实现==或Equals()。我对你的答案在这里有复杂的感受。 – 2011-05-18 07:11:29

+0

'Component.For'是一个工厂,每次都会返回一个新的实例。默认情况下,对象通过引用进行比较,并且由于它们不是不可变的值对象,所以它们不会覆盖Object.Equals来进行值比较。 – 2011-05-18 07:23:49

+0

不,您测试的所有内容都是在测试方法开始时您已经正确反转了工程的Castle Windsor代码。如果你想要一个更好的集成测试,把Castle当作黑箱,不要嘲笑它,设置你的记录器,然后验证它是否记录了事情。这样你就可以验证整个解决方案的工作。 – 2011-05-18 07:30:26