简体   繁体   中英

How to test that an event will not be fired in xUnit?

I have two questions.

  1. Does it make sense to test that an event will not be fired?
  2. If yes, what is the best way to accomplish that using the xUnit framework?

For example, I have a class with a single property Mark ,

public class Box : INotifyPropertyChanged
{
  private Marking mark = Marking.None;

  public Marking Mark
  {
    get
    {
      return mark;
    }
    set
    {
      mark = value;
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Mark)));
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
}

and I want to test that when someone is going to set the value of Mark to the same value as the property points currently, then the PropertyChanged event will not be fired.

1) Yes, it makes perfect sense. If the requirement is that an event should not be fired under certain circumstances, then there should be a test for it.

2) Something like this:

[Fact]
public void PropertyChangedNotFired()
{
    Box box = new Box();

    int fireCount = 0;

    box.PropertyChanged += (s, e) => ++fireCount;

    box.Mark = Marking.Tick;

    Assert.Equal(1, fireCount); // Sanity check. Not strictly speaking following AAA

    box.Mark = Marking.Tick;

    Assert.Equal(1, fireCount); // If we get 2, event has wrongly fired
}

This assumes an enum (which you didn't show) something like:

public enum Marking { None, Tick, Cross }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM