Search code examples
.netunit-testingncover

Unit test the code of an event handler


How do I test the code of an event handler?

I have this

    [TestMethod]
    [ExpectedException(typeof(XmlException))]
    public void TheXMLValidationEventHandlerWorksOK()
    {
        string xSDFilePath = @"XML Test Files\wrongXSDFile.xsd";
        try
        {
            XmlSchema xmlSchema = XmlSchema.Read(new StreamReader(xSDFilePath), XMLValidationEventHandler);
        }
        catch (System.Xml.XmlException e)
        {
            Assert.IsNotNull(e);
            throw e;
        }
    }

    private void XMLValidationEventHandler(object sender, ValidationEventArgs e)
    {
        throw e.Exception;
    }

But NCover states that the code of the event handlet itself is NOT tested ('thow e.Exception' is marked in red).

May I have to try to call directly to the event handler method? How do I create an instance of ValidationEventArgs?


Solution

  • There is couple of issues in the Test. For

     [ExpectedException(typeof(XmlException))]
    

    Use XmlSchemaException

     [ExpectedException(typeof(XmlSchemaException))]
    

    In your test name provide exactly what you expecting. For example

     public void InvalidXmlSchema_EventHandlerExecutes_ThrowsXmlSchemaException()
    

    You also don't need try{} catch{} blocks. The correct exception type would propagate and handled by the ExpectedException Attr.

    Keep in mind that since you are the file system to read the wrongXSDFile.xsd this is not a Unit Test. This is an integration test. The test would throw an XmlSchemaException. Below is test would pass for invalid XSD.

        [TestMethod]
        [ExpectedException(typeof(XmlSchemaException))]
        public void InvalidXmlSchema_EventHandlerExecutes_ThrowsXmlSchemaException() {
            string xSDFilePath = @"XML Test Files\wrongXSDFile.xsd";
            XmlSchema.Read(new StreamReader(xSDFilePath), XMLValidationEventHandler);
        }
    
        private void XMLValidationEventHandler(object sender, ValidationEventArgs e){
            throw e.Exception;
        }