c# - NSubstitute 和 AutoFixture 与 Received 相关的问题

标签 c# unit-testing autofixture nsubstitute

我对 NSubsitute 的 Received() 方法有问题。

我的测试类:

private readonly IFixture _fixture;

    public NotificationsCenterTests()
    {
        _fixture = new Fixture();
        _fixture.Behaviors.Add(new OmitOnRecursionBehavior());
        _fixture.Customize(new AutoNSubstituteCustomization());
    }

这个方法效果很好:

[Theory, AutoNSubstituteData]
    public void Send_NotificationIsNotNull_NotificationShouldBeSendAndSaved(
        IDocumentDbRepository<NotificationDocument> repository,
        Notification notification
        )
    {
        // Arrange
        var sender = Substitute.For<INotificationSender>();

        var notificationsCenter = new NotificationsCenter(
            sender, repository);
        // Act
        Func<Task> action = async () => await notificationsCenter.SendAsync(notification);

        // Assert
        action.Invoke();
        sender.Received(1).Send(Arg.Any<Notification>());
    }

这会发送错误:

[Theory, AutoNSubstituteData]
    public void Send_NotificationIsNotNull_NotificationShouldBeSendAndSaved2(
        INotificationSender sender,
        IDocumentDbRepository<NotificationDocument> repository,
        NotificationsCenter notificationsCenter,
        Notification notification
        )
    {
        // Act
        Func<Task> action = async () => await notificationsCenter.SendAsync(notification);

        // Assert
        action.Invoke();
        sender.Received(1).Send(Arg.Any<Notification>());
    }

它是我的 autonsubsisute 属性:

internal class AutoNSubstituteDataAttribute : AutoDataAttribute
{
    public AutoNSubstituteDataAttribute()
        : base(new Fixture()
            .Customize(new AutoNSubstituteCustomization()))
    {
    }
}

方法2的错误是:

NSubstitute.Exceptions.ReceivedCallsException : Expected to receive exactly 1 call matching:
    Send(any Notification)
Actually received no matching calls.

这是怎么回事?我想用 TDD 编写一些代码,但我已经停在这个小问题上了。我不知道第二个代码有什么问题。

你有什么想法吗?

最佳答案

在第二个示例中,NotificationsCenter 是使用 repositorysender不同实例创建的。

虽然 repositorysender 是在 NotificationsCenter 参数之前声明的,但这并不意味着会重用同一个实例。

您需要为此使用[Frozen] 属性,如以下资源所示:

关于c# - NSubstitute 和 AutoFixture 与 Received 相关的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38374061/

相关文章:

c# - JSON 基于字典键推断类类型

c# - 如何获取 NHibernate 中的预计属性?

javascript - 在 mocha 单元测试中包含模块

c# - 用于创建基类型实现的自定义

具有派生类型的 AutoFixture

c# - 如何将控制台应用程序转换为 Windows 服务?

c# - 将 C# 泛型类型作为参数传递

C++ Google Mock - EXPECT_CALL() - 不直接调用时期望不起作用

java - 如何在单元测试中模拟 JPA 存储库的保存方法

c# - 随机枚举生成