我用nsubstitue正确制作假货吗?

时间:2015-10-07 02:46:48

标签: c# unit-testing nsubstitute isolation-frameworks

我接受了一项任务,了解如何使用隔离框架。我想知道我是否正在以nsubstitute的方式创建假货。以下是应用程序如何看起来像Here的序列图。

然后我做了单元测试并交付了练习。有人告诉我,我没有使用隔离框架来创建假货(而不是之前我们将它们自己制作)。以下是我的两个测试的示例:

    [Test]
    public void RequestEntry_WithValidId_DoorStateIsClosed()
    {
        var door = new Door();
        var alarm = new Alarm();
        var userValidation = new UserValidation();
        var entryNotifier = Substitute.For<IEntryNotification>();
        var uut = new DoorControl(userValidation, entryNotifier, door, alarm);
        door.DoorCtrl = uut;
        uut.RequestEntry(1);
        Assert.That(uut.DState == DoorState.Closed);
        entryNotifier.Received(1).EntryNotificationGranted();
    }

        public void RequestEntry_WithValidId_DoorOpens()
    {
        var door = Substitute.For<IDoor>();
        var alarm = new Alarm();
        var userValidation = new UserValidation();
        var entryNotifier = new EntryNotification();
        var uut = new DoorControl(userValidation, entryNotifier, door, alarm);
        door.DoorCtrl = uut;
        uut.RequestEntry(1);
        door.Received(1).Open();
    }

所以我知道在这两个测试中都有一些问题,因为我需要两个存根,所以我稍微改了一下,所以他们知道这样:

        public void RequestEntry_WithValidId_CorrectIdParsedToUserValidation()
    {
        var door = Substitute.For<IDoor>();
        var alarm = new Alarm();
        var userValidation = Substitute.For<IUserValidation>();
        userValidation.ValidateEntryRequest(Arg.Any<int>()).Returns(true);
        var entryNotifier = Substitute.For<IEntryNotification>();
        var uut = new DoorControl(userValidation, entryNotifier, door, alarm);
        door.DoorCtrl = uut;
        uut.RequestEntry(1);
        userValidation.Received(1).ValidateEntryRequest(1);
    }

        public void RequestEntry_WithValidId_DoorOpens()
    {
        var door = Substitute.For<IDoor>();
        var alarm = new Alarm();
        var userValidation = Substitute.For<IUserValidation>();
        userValidation.ValidateEntryRequest(Arg.Any<int>()).Returns(true);
        var entryNotifier = Substitute.For<IEntryNotification>();
        var uut = new DoorControl(userValidation, entryNotifier, door, alarm);
        door.DoorCtrl = uut;
        uut.RequestEntry(1);
        door.Received(1).Open();
    }

我正确使用nsubstitute吗?或者我是否还需要添加其他一些东西(在这两个测试用例中没有使用Alarm类,但是DoorControl构造函数的参数需要它,所以我看不出存根的原因)?

1 个答案:

答案 0 :(得分:1)

是的,您正确使用NSubstitute。我不可能知道你是否应该测试别的东西而不是你做过的东西。