Nerf
Nerf

Reputation: 938

NSubstitute and AutoFixture issue with Received

I have problem with Received() method from NSubsitute.

My test class:

private readonly IFixture _fixture;

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

This method works good:

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

And this sends error:

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

It my autonsubsisute attribute:

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

And the error in method 2 is:

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

What is going on? I want do some code with TDD but I have stopped at this little issue. And I dont have idea what is wrong with the second code.

Do you have any thoughts?

Upvotes: 2

Views: 660

Answers (1)

Nikos Baxevanis
Nikos Baxevanis

Reputation: 11201

In the second example, NotificationsCenter is created with different instances for repository and sender.

Although repository and sender are declared before the NotificationsCenter argument, that doesn't mean that the same instance is reused.

You need to use the [Frozen] attribute for this, as shown in the following resources:

Upvotes: 2

Related Questions