unit testing a class with event and delegate

后端 未结 3 1910
北恋
北恋 2020-12-30 16:20

I am new to testing please help.

I have the following class

public delegate void OnInvalidEntryMethod(ITnEntry entry, string message);

public class          


        
3条回答
  •  自闭症患者
    2020-12-30 16:37

    It's probably simplest just to subscribe to the event using an anonymous method:

    [Test]
    public void IsValidEntry_WithValidValues()
    {
        _selectedEntry = MakeEntry(_ticker);
        _entryValidator.OnInvalidEntry += delegate { 
            Assert.Fail("Shouldn't be called");
        };
    
        Assert.IsTrue(_entryValidator.IsValidEntry(_selectedEntry, _selectedEntry.Ticker));
    }    
    
    [Test]
    public void IsValidEntry_WithInValidTicker()
    {
        bool eventRaised = false;
        _selectedEntry = MakeEntry("");
        _entryValidator.OnInvalidEntry += delegate { eventRaised = true; };
    
        Assert.IsFalse(_entryValidator.IsValidEntry(_selectedEntry, _selectedEntry.Ticker));
        Assert.IsTrue(eventRaised);
    }
    

    In the second test you might want to validate that the event arguments were as expected too.

    Also note that "invalid" is one word - so your test should be IsValidEntry_WithInvalidTicker. I'd also not bother with the setup - I'd just declare new local variables in each test.

提交回复
热议问题