【问题标题】:Unit Test INotifyPropertyChanged using Rhino Mocks使用 Rhino Mocks 进行单元测试 INotifyPropertyChanged
【发布时间】:2020-01-23 07:30:35
【问题描述】:

我有一个实现 INotifyPropertyChanged 的​​类,我需要测试这个接口是否正确实现。我想使用 Rhino Mock 对象来做到这一点。

class MyClass : INotifyPropertyChanged
{
    public int X
    {
        get => ...;
        set => ... // should check if value changes and raise event PropertyChanged
    }
}

我要测试的是,当 X 更改值时,该事件 PropertyChanged 仅调用一次,并带有适当的参数。

MyClass testObject = new MyClass();

// the mock:
PropertyChangedEventHandler a = MockRepository.GenerateMock<PropertyChangedEventHandler>();
testObject.PropertyChanged += a;

// expect that the mock will be called exactly once, with the proper parameters
a.Expect( (x) => ???)
 .Repeat()
 .Once();

// change X, and verify that the event handler has been called exactly once
testObject.X = testObject.X + 1;

a.VerifyAllExpectations(); ???

我认为我走在正确的道路上,但我无法让它发挥作用。

【问题讨论】:

    标签: c# unit-testing inotifypropertychanged rhino-mocks


    【解决方案1】:

    有时候,如果没有使用实物的连锁反应,真的不需要使用模拟。

    以下简单示例创建委托的实例并验证预期行为

    我要测试的是,当 X 更改值时,该事件 PropertyChanged 仅调用一次,并带有适当的参数。

    [TestClass]
    public class MyClassTests {
        [TestMethod]
        public void Should_Call_PropertyChanged_Once() {
            //Arrange            
            //Store calls
            IDictionary<string, int> properties = new Dictionary<string, int>();
            PropertyChangedEventHandler handler = new PropertyChangedEventHandler((s, e) => {
                if (!properties.ContainsKey(e.PropertyName))
                    properties.Add(e.PropertyName, 0);
    
                properties[e.PropertyName]++;
            });
    
            MyClass testObject = new MyClass();
            testObject.PropertyChanged += handler;
    
            string expectedPropertyName = nameof(MyClass.X);
            int expectedCount = 1;
    
            //Act
            testObject.X = testObject.X + 1;
    
            //Assert - using FluentAssertions
            properties.Should().ContainKey(expectedPropertyName);
            properties[expectedPropertyName].Should().Be(expectedCount);
        }
    
        class MyClass : INotifyPropertyChanged {
            public event PropertyChangedEventHandler PropertyChanged = delegate { };
    
            void raisePropertyChanged([CallerMemberName]string propertyName = null) {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
    
            int x;
            public int X {
                get => x;
                set {
                    if (value != x) {
                        x = value;
                        raisePropertyChanged();
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      相关资源
      最近更新 更多