Test di unità che generano eventi in C # (in ordine)


160

Ho del codice che genera PropertyChangedeventi e vorrei essere in grado di testare l'unità che gli eventi vengono generati correttamente.

Il codice che sta generando gli eventi è simile

public class MyClass : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;  

   protected void NotifyPropertyChanged(String info)
   {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
   }  

   public string MyProperty
   {
       set
       {
           if (_myProperty != value)
           {
               _myProperty = value;
               NotifyPropertyChanged("MyProperty");
           }
       }
   }
}

Ottengo un bel test verde dal seguente codice nei test delle mie unità, che utilizza i delegati:

[TestMethod]
public void Test_ThatMyEventIsRaised()
{
    string actual = null;
    MyClass myClass = new MyClass();

    myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
    {
         actual = e.PropertyName;
    };

    myClass.MyProperty = "testing";
    Assert.IsNotNull(actual);
    Assert.AreEqual("MyProperty", actual);
}

Tuttavia, se provo a mettere insieme le impostazioni delle proprietà in questo modo:

public string MyProperty
{
    set
    {
        if (_myProperty != value)
        {
            _myProperty = value;
            NotifyPropertyChanged("MyProperty");
            MyOtherProperty = "SomeValue";
        }
    }
}

public string MyOtherProperty
{
    set
    {
        if (_myOtherProperty != value)
        {
            _myOtherProperty = value;
            NotifyPropertyChanged("MyOtherProperty");
        }
    }
}

Il mio test per l'evento ha esito negativo: l'evento che acquisisce è l'evento per MyOtherProperty.

Sono abbastanza sicuro che l'evento si attivi, la mia IU reagisce come fa, ma il mio delegato cattura solo l'ultimo evento da attivare.

Quindi mi chiedo:
1. Il mio metodo di test degli eventi è corretto?
2. Il mio metodo per generare eventi concatenati è corretto?

Risposte:


190

Tutto ciò che hai fatto è corretto, a condizione che tu voglia che il tuo test chieda "Qual è l'ultimo evento che è stato generato?"

Il tuo codice sta generando questi due eventi, in questo ordine

  • Proprietà modificata (... "La mia proprietà" ...)
  • Proprietà modificata (... "MyOtherProperty" ...)

Se questo è "corretto" o no dipende dallo scopo di questi eventi.

Se si desidera verificare il numero di eventi che vengono generati e l'ordine in cui vengono generati, è possibile estendere facilmente il test esistente:

[TestMethod]
public void Test_ThatMyEventIsRaised()
{
    List<string> receivedEvents = new List<string>();
    MyClass myClass = new MyClass();

    myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
    {
        receivedEvents.Add(e.PropertyName);
    };

    myClass.MyProperty = "testing";
    Assert.AreEqual(2, receivedEvents.Count);
    Assert.AreEqual("MyProperty", receivedEvents[0]);
    Assert.AreEqual("MyOtherProperty", receivedEvents[1]);
}

13
Versione più breve: myClass.PropertyChanged + = (mittente oggetto, e) => paidEvents.Add (e.PropertyName);
ShloEmi,

22

Se stai eseguendo TDD, i test degli eventi possono iniziare a generare molto codice ripetitivo. Ho scritto un monitor di eventi che consente un approccio molto più pulito alla scrittura di test unitari per queste situazioni.

var publisher = new PropertyChangedEventPublisher();

Action test = () =>
{
    publisher.X = 1;
    publisher.Y = 2;
};

var expectedSequence = new[] { "X", "Y" };

EventMonitor.Assert(test, publisher, expectedSequence);

Per ulteriori dettagli, vedere la mia risposta a quanto segue.

Test unitari che un evento viene generato in C #, usando la riflessione


3
Il secondo collegamento non è attivo.
Lennart,

10

Questo è molto vecchio e probabilmente non verrà nemmeno letto, ma con alcune nuove fantastiche funzionalità .net ho creato una classe INPC Tracer che consente che:

[Test]
public void Test_Notify_Property_Changed_Fired()
{
    var p = new Project();

    var tracer = new INCPTracer();

    // One event
    tracer.With(p).CheckThat(() => p.Active = true).RaisedEvent(() => p.Active);

    // Two events in exact order
    tracer.With(p).CheckThat(() => p.Path = "test").RaisedEvent(() => p.Path).RaisedEvent(() => p.Active);
}

Vedi gist: https://gist.github.com/Seikilos/6224204


Bello - dovresti considerare di confezionarlo e pubblicarlo su nuget.org
Simon Ejsing il

1
Ottimo lavoro! Ho davvero scavato l'API fluente. Anch'io ho fatto qualcosa di simile ( github.com/f-tischler/EventTesting ) ma penso che il tuo approccio sia ancora più conciso.
Florian Tischler,

6

Di seguito è riportato un codice Andrew leggermente modificato che invece di registrare semplicemente la sequenza di eventi generati conta piuttosto quante volte è stato chiamato un evento specifico. Sebbene sia basato sul suo codice, lo trovo più utile nei miei test.

[TestMethod]
public void Test_ThatMyEventIsRaised()
{
    Dictionary<string, int> receivedEvents = new Dictionary<string, int>();
    MyClass myClass = new MyClass();

    myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
    {
        if (receivedEvents.ContainsKey(e.PropertyName))
            receivedEvents[e.PropertyName]++;
        else
            receivedEvents.Add(e.PropertyName, 1);
    };

    myClass.MyProperty = "testing";
    Assert.IsTrue(receivedEvents.ContainsKey("MyProperty"));
    Assert.AreEqual(1, receivedEvents["MyProperty"]);
    Assert.IsTrue(receivedEvents.ContainsKey("MyOtherProperty"));
    Assert.AreEqual(1, receivedEvents["MyOtherProperty"]);
}

1

Sulla base di questo articolo, ho creato questo semplice assistente di asserzione:

private void AssertPropertyChanged<T>(T instance, Action<T> actionPropertySetter, string expectedPropertyName) where T : INotifyPropertyChanged
    {
        string actual = null;
        instance.PropertyChanged += delegate (object sender, PropertyChangedEventArgs e)
        {
            actual = e.PropertyName;
        };
        actionPropertySetter.Invoke(instance);
        Assert.IsNotNull(actual);
        Assert.AreEqual(propertyName, actual);
    }

Con questo metodo di supporto, il test diventa davvero semplice.

[TestMethod()]
public void Event_UserName_PropertyChangedWillBeFired()
{
    var user = new User();
    AssertPropertyChanged(user, (x) => x.UserName = "Bob", "UserName");
}

1

Non scrivere un test per ogni membro - questo è molto lavoro

(forse questa soluzione non è perfetta per ogni situazione, ma mostra un modo possibile. Potrebbe essere necessario adattarla al caso d'uso)

È possibile utilizzare la riflessione in una libreria per verificare se tutti i membri rispondono correttamente all'evento di modifica della proprietà:

  • L'evento PropertyChanged viene generato all'accesso del setter
  • L'evento viene generato correttamente (il nome della proprietà è uguale all'argomento dell'evento generato)

Il seguente codice può essere utilizzato come libreria e mostra come testare la seguente classe generica

using System.ComponentModel;
using System.Linq;

/// <summary>
/// Check if every property respons to INotifyPropertyChanged with the correct property name
/// </summary>
public static class NotificationTester
    {
        public static object GetPropertyValue(object src, string propName)
        {
            return src.GetType().GetProperty(propName).GetValue(src, null);
        }

        public static bool Verify<T>(T inputClass) where T : INotifyPropertyChanged
        {
            var properties = inputClass.GetType().GetProperties().Where(x => x.CanWrite);
            var index = 0;

            var matchedName = 0;
            inputClass.PropertyChanged += (o, e) =>
            {
                if (properties.ElementAt(index).Name == e.PropertyName)
                {
                    matchedName++;
                }

                index++;
            };

            foreach (var item in properties)
            { 
                // use setter of property
                item.SetValue(inputClass, GetPropertyValue(inputClass, item.Name));
            }

            return matchedName == properties.Count();
        }
    }

I test della tua classe ora possono essere scritti come. (forse vuoi dividere il test in "evento c'è" e "evento generato con il nome corretto" - puoi farlo tu stesso)

[TestMethod]
public void EveryWriteablePropertyImplementsINotifyPropertyChangedCorrect()
{
    var viewModel = new TestMyClassWithINotifyPropertyChangedInterface();
    Assert.AreEqual(true, NotificationTester.Verify(viewModel));
}

Classe

using System.ComponentModel;

public class TestMyClassWithINotifyPropertyChangedInterface : INotifyPropertyChanged
{
        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }

        private int id;

        public int Id
        {
            get { return id; }
            set { id = value;
                NotifyPropertyChanged("Id");
            }
        }
}

Ho provato questo, ma se i miei setter di proprietà hanno una dichiarazione di guardia come "if (value == _myValue) return", cosa che tutti i miei fanno, allora quanto sopra non funzionerà, a meno che non mi manchi qualcosa. Di recente vengo dal C ++ al C #.
codah,

0

Ho fatto un'estensione qui:

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;
    }
}

C'è l'uso:

   [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());

    }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.