NUnit是否提供了断言对象事件被订阅的方法?

时间:2010-02-18 10:20:32

标签: c# unit-testing nunit

我有一个对象作为参数传递给方法。这个对象上有一个事件,当我以对象作为参数调用此方法时,它应该被订阅。

NUnit允许我查看吗?

编辑:添加了代码示例:

    [Test]
    public void AddingToCollectionShouldHookPropertyChangedEventUp()
    {
        // Arrange:
        var viewModel = new viewModel();
        var viewModelCollection = new viewModelCollection();

        // Act:
        viewModelCollection.AddViewModel(viewModel);

        // Assert that the property changed event is hooked up in some way:
        // This is commented out because I cannot do this. I left it here to  
        // illustrate what I want to achieve:
        //blockViewModel.PropertyChanged.Should().Not.Be.Null();
    }

2 个答案:

答案 0 :(得分:3)

你无法了解事件的状态;按照设计,你只能注册它+ =或取消注册 - =。因此,NUnit没有提供任何扩展或其他机制来测试已订阅的事件。

如果事件在界面上,您可以通过模拟类(您自己的或框架的模拟,如Rhino)测试订阅。

您无论如何都可以测试事件的行为!

如果您发布一些代码,我相信有人会帮助您进行有意义的测试。这是一个虚拟的示例,为您提供一些想法:

[Test]
public void ChangingTheWhateverProperty_TriggersPropertyChange()
    {

        // Create anonymous delegate which is also your test assertion
        PropertyChangedEventHandler anonymousDelegate = (sender, e) => Assert.AreEqual("Whatever", e.PropertyName);

        // Subscribe to the needed event
        vm.PropertyChanged += anonymousDelegate;

        // trigger the event
        vm.Whatever = "blah";
    }

HTH,
Berryl

===使用您的代码修改示例=======

[Test]
    public void AddingToCollectionShouldHookPropertyChangedEventUp()
    {
        // Arrange: 
        var viewModel = new viewModel();
        var viewModelCollection = new viewModelCollection();

        // This *IS* your assert also, and will get called back when you Act
        // The only part you need to supply for this test is the property that gets fired when you add a viewmodel
        PropertyChangedEventHandler anonymousDelegate = (sender, e) => Assert.AreEqual("Whatever", e.PropertyName);

        // Subscribe to the needed event 
        viewModelCollection.PropertyChanged += anonymousDelegate;

        // Act: 
        viewModelCollection.AddViewModel(viewModel);
    }

===事件登记的示例rhino测试=====

   [Test]
    public void Test()
    {
        var mockCorpseKicker = MockRepository.GenerateMock<INotifyPropertyChanged>();
        mockCorpseKicker.PropertyChanged += null;
        mockCorpseKicker.AssertWasCalled(x => x.PropertyChanged += Arg<PropertyChangedEventHandler>.Is.Anything);
    }

答案 1 :(得分:-1)

您可以检查事件是否为空。如果它有订阅者,则它不会为空。

相关问题