我对 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
是使用 repository
和 sender
的不同实例创建的。
虽然 repository
和 sender
是在 NotificationsCenter
参数之前声明的,但这并不意味着会重用同一个实例。
您需要为此使用[Frozen]
属性,如以下资源所示:
关于c# - NSubstitute 和 AutoFixture 与 Received 相关的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38374061/