2013-11-23 250 views
0

如何测试事件处理程序的代码?单元测试事件处理程序的代码

我有这个

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

但NCover指出,事件的代码handlet本身不是测试(“thow e.Exception”被标记为红色)。

我可以尝试直接调用事件处理程序方法吗?我如何创建ValidationEventArgs的实例?

回答

0

在测试中有几个问题。对于

[ExpectedException(typeof(XmlException))] 

使用XmlSchemaException

[ExpectedException(typeof(XmlSchemaException))] 

在您的测试名称提供正是你期待什么。例如

public void InvalidXmlSchema_EventHandlerExecutes_ThrowsXmlSchemaException() 

您也不需要尝试{} catch {}块。正确的异常类型会传播并由ExpectedException属性处理。

请记住,由于您是读取错误的文件系统XSDFile.xsd,因此这不是单元测试。这是一个集成测试。测试会抛出一个XmlSchemaException。以下是测试将通过无效的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; 
    } 
+0

我正在检查所有帖子,我忘记标记为答案。抱歉耽搁了 – Kaikus