为什么不满足犀牛模拟的期望?

时间:2010-09-10 21:00:55

标签: c# unit-testing rhino-mocks mbunit

这是代码:

public interface IAccessPoint
{
    int BackHaulMaximum { get; set; }

    bool BackHaulMaximumReached();
    void EmailNetworkProvider();
}

public class AccessPoint : IAccessPoint
{
    private IMailProvider Mailer { get; set; }

    public AccessPoint(IMailProvider provider)
    {
        this.Mailer = provider ?? new DefaultMailProvider();
    }

    public int BackHaulMaximum { get; set; }

    public bool BackHaulMaximumReached()
    {
        if (BackHaulMaximum > 80)
        {
            EmailNetworkProvider();
            return true;
        }
        return false;
    }


    public void EmailNetworkProvider()
    {
        this.Mailer.SendMail();
    }
}

public interface IMailProvider
{
    void SendMail();
}

public class DefaultMailProvider : IMailProvider
{
    public void SendMail()
    {

    }
}

// Here is the Test, It is not calling EmailNetworkProvider which calls SendMail()

[TestFixture]
public class Tests
{
    [Test]
    public void NetworkProviderShouldBeEmailedWhenBackHaulMaximumIsReached()
    {
        var mailerMock = MockRepository.GenerateMock<IMailProvider>();

        mailerMock.Expect(x => x.SendMail());

        var accessPoint = new AccessPoint(mailerMock);

        accessPoint.BackHaulMaximum = 81;

        Assert.IsTrue(accessPoint.BackHaulMaximumReached());

        mailerMock.VerifyAllExpectations();
    }
}

1 个答案:

答案 0 :(得分:1)

如果使用此测试会有任何改进吗?

[Test]
public void NetworkProviderShouldBeEmailedWhenBackHaulMaximumIsReached()
{
    var mailerMock = MockRepository.GenerateStub<IMailProvider>();
    var accessPoint = new AccessPoint(mailerMock);

    accessPoint.BackHaulMaximum = 81;

    var actual = accessPoint.BackHaulMaximumReached();

    Assert.AreEqual(true, actual);
    mailerMock.AssertWasCalled(x => x.SendMail());
}

作为旁注,BackhaulMaximumReached()是一种奇怪的设计。除非消费者检查是否达到了回程最大值,否则不会发出通知,无论BackHaulMaximum的值是多少。

以这种方式混合命令和查询在语义上是令人困惑的。