Unit testing that events are raised in C# (in order)

前端 未结 7 2277
小蘑菇
小蘑菇 2020-11-29 16:02

I have some code that raises PropertyChanged events and I would like to be able to unit test that the events are being raised correctly.

The code that i

7条回答
  •  自闭症患者
    2020-11-29 16:50

    I've made an extension here:

    public static class NotifyPropertyChangedExtensions
    {
        private static bool _isFired = false;
        private static string _propertyName;
    
        public static void NotifyPropertyChangedVerificationSettingUp(this INotifyPropertyChanged notifyPropertyChanged,
          string propertyName)
        {
            _isFired = false;
            _propertyName = propertyName;
            notifyPropertyChanged.PropertyChanged += OnPropertyChanged;
        }
    
        private static void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == _propertyName)
            {
                _isFired = true;
            }
        }
    
        public static bool IsNotifyPropertyChangedFired(this INotifyPropertyChanged notifyPropertyChanged)
        {
            _propertyName = null;
            notifyPropertyChanged.PropertyChanged -= OnPropertyChanged;
            return _isFired;
        }
    }
    

    There is the usage:

       [Fact]
        public void FilesRenameViewModel_Rename_Apply_Execute_Verify_NotifyPropertyChanged_If_Succeeded_Through_Extension_Test()
        {
            //  Arrange
            _filesViewModel.FolderPath = ConstFolderFakeName;
            _filesViewModel.OldNameToReplace = "Testing";
            //After the command's execution OnPropertyChanged for _filesViewModel.AllFilesFiltered should be raised
            _filesViewModel.NotifyPropertyChangedVerificationSettingUp(nameof(_filesViewModel.AllFilesFiltered));
            //Act
            _filesViewModel.ApplyRenamingCommand.Execute(null);
            // Assert
            Assert.True(_filesViewModel.IsNotifyPropertyChangedFired());
    
        }
    

提交回复
热议问题