2009-10-05 89 views
2

我很努力了解新的AAA语法在Rhino Mocks中的工作原理。我的大多数测试如下所示:Rhino Mocks的新语法

[Test] 
    public void Test() 
    { 
     //Setup 
     ISth sth= mocks.DynamicMock<ISth>(); 

     //Expectations 
     Expect.Call(sth.A()).Return("sth"); 

     mocks.ReplayAll(); 
     //Execution 
     FunctionBeingTested(sth); 
     //...asserts, etc 

     //Verification 
     mocks.VerifyAll(); 
    } 

它会如何使用AAA语法?从Ayende`s博客

回答

3

最有可能是这样的:

[Test] 
public void Test() 
{ 
    // Arrange 
    ISth sth= MockRepository.GenerateMock<ISth>(); 

    sth 
     .Stub(x => x.A()) 
     .Return("sth"); 

    // Act 
    FunctionBeingTested(sth); 

    // Assert 
} 

要真正从新AAA语法中获益,你必须改变你的想法一点。我尝试解释。

我的建议存在一个主要区别:没有“预期验证”。所以我建议不要期待这个调用,因为有一个返回值。我假设该方法在没有调用sth.A时无法通过测试,因为它会错过正确的返回值。它至少会失败其中一个断言。

这实际上是一件好事。

  • 你可以将Stub移动到TestInitialize,当测试中没有调用stubbed方法时(这不是期望值),它不会伤害。你的测试会变得更短。
  • 您的测试不知道“如何”测试系统完成这项工作,您只检查结果。您的测试将变得更加可维护。

还有另外一种情况,你确实需要检查的方法已呼吁模拟。主要是如果它返回无效。例如:事件应该已经被解雇,交易已经完成,等等。使用AssertWasCalled此:

[Test] 
public void Test() 
{ 
    // Arrange 
    ISth sth= MockRepository.GenerateMock<ISth>(); 

    // Act 
    FunctionBeingTested(sth); 

    // Assert 
    sth 
     .AssertWasCalled(x => x.A()); 
} 

注:没有返回值,所以没有存根。这是一个理想的情况。当然,你可以同时拥有两个,分别是StubAssertWasCalled


还有ExpectVerifyAllExpectations,这实际上表现为旧的语法。我只会在你使用时需要StubAssertWasCalled在相同的测试中,你有完整的参数约束,你不想写两次。通常,避免ExpectVerifyAllExpectations

1

例如:

[Test] 
public void WhenUserForgetPasswordWillSendNotification_UsingExpect() 
{ 
    var userRepository = MockRepository.GenerateStub<IUserRepository>(); 
    var notificationSender = MockRepository.GenerateMock<INotificationSender>(); 

    userRepository.Stub(x => x.GetUserById(5)).Return(new User { Id = 5, Name = "ayende" }); 
    notificationSender.Expect(x => x.Send(null)).Constraints(Text.StartsWith("Changed")); 

    new LoginController(userRepository, notificationSender).ForgotMyPassword(5); 

    notificationSender.VerifyAllExpectations(); 
} 

的变化在你的测试

[Test] 
    public void Test() 
    { 
     //Arrange 
     var sth= MockRepository.GenerateMock<ISth>(); 
     sth.Expect(x=>sth.A()).Return("sth"); 

     //Act 
     FunctionBeingTested(sth); 

     //Assert 
     sth.VerifyAllExpectations(); 
    } 

但是,这只是一个长镜头。写下它,因为我怀疑它是。