English 中文(简体)
Rhino Mocks的新辛子
原标题:The new syntax for Rhino Mocks
  • 时间:2009-10-05 13:13:55
  •  标签:

我正在挣扎一比,以了解新的AAAyntax在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 syntax?

最佳回答

很可能如此:

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

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

    // Act
    FunctionBeingTested(sth);

    // Assert
}

为了真正得益于新的阿农联的辛迪加,你必须改变你的思维。 我试图解释。

我的建议存在重大差别:不存在“特殊性-脆弱性”。 因此,我提议不希望发出这一呼吁,因为有回报价值。 我假设,这种方法在打上“<代码>sth.A时可以通过测试,因为它会错失正确的回报价值。 它至少将失败另一人的说法之一。

这实际上是一件好事。

  • you can move the Stub to TestInitialize, it does not hurt when the stubbed method is not called in a test (it s not an expectation). Your tests will become shorter.
  • Your test does not know "how" the system under test does the job, you only check the results. Your tests will become more maintainable.

还有一种情况是,如果有人要求采取某种方法,实际上需要检查。 主要如果它恢复无效。 例如:本来就应当发射一次事件、所进行交易等等。 使用<编码>AssertWasCalled

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

    // Act
    FunctionBeingTested(sth);

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

注:没有回报价值,因此没有Stub。 这是一个理想的情况。 当然,你可以有<代码>Stub和AssertWasCalled


还有<代码>Expect和Verification AllExpectations,它们实际上与旧的辛加一样。 只有在以下情况下才会使用:need>code>Stub和AssertWasCalled。 通常情况下,aaveExpect

问题回答

Ayende's blog的例子:

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

但是,这只是一次长枪。 把它说成是怀疑。





相关问题