繁体   English   中英

如何使用XDocument.Load()测试方法

[英]How to test methods with XDocument.Load()

我有以下代码:

void Foo(string path){
    try{
        XDocument document = XDocument.Load(path);
        Validate(document);
        //Some logic
    }
    catch(Exception ex){
        //Some logic
    }
}
void Validate(XDocument document){
     XmlSchemaSet schema = new XmlSchemaSet();
     schema.Add("", XmlReader.Create(new StringReader("XsdFile")));
     document.Validate(schema, null);
}

如何测试这种方法? 我想检查以下三种情况:-正确的XML-错误的XML-非XML(例如路径中的.bmp文件)我正在使用Visual Studio测试。

运行测试时,可以使用[DeploymentItem]属性来部署其他文件。 它们将被复制到TestContext.TestDeploymentDir

// assume this XML file is in the root of the test project, 
// and "Copy to Output Directory" property of the file is set to "Copy always"
const string ValidXmlFileName = "valid.xml"; 

[TestMethod]
[DeploymentItem(ValidXmlFileName)]
public void Validate_ValidXml_ShouldBeOk() {

    string path = Path.Combine(TestContext.TestDeploymentDir, ValidXmlFileName);

    // perform test with the deployed file ...
}

进一步阅读: 如何:部署测试文件

该代码与静态实现问题紧密相关,给出的标题和问题使我相信这是一个XY问题

为了解决此代码的缺点,需要对其进行重构,以使其与实现问题脱钩。

如以下示例所示,可以将文档的实际加载和验证委托给他们自己的关注点

public interface IDocumentLoader<T> where T : class {
    T Load(string path);
}

public interface IXDocumentLoader : IDocumentLoader<XDocument> { }
public class XDocumentLoader : IXDocumentLoader {
    public XDocument Load(string path) {
        return XDocument.Load(path);
    }
}

public interface IDocumentValidator<T> where T : class {
    void Validate(T document);
}

public interface IXDocumentValidator : IDocumentValidator<XDocument> { }
public class XDocumentValidator : IXDocumentValidator {
    public void Validate(XDocument document) {
        XmlSchemaSet schema = new XmlSchemaSet();
        schema.Add("", XmlReader.Create(new StringReader("XsdFile")));
        document.Validate(schema, null);
    }
}

public class Subject {
    private IXDocumentLoader loader;
    private IXDocumentValidator validator;

    public Subject(IXDocumentLoader loader, IXDocumentValidator validator) {
        this.loader = loader;
        this.validator = validator;
    }

    public void Foo(string path) {
        try {
            XDocument document = loader.Load(path);
            validator.Validate(document);
            //Some logic
        } catch (Exception ex) {
            //Some logic
        }
    }
}

原始示例中提供的大多数登录信息已被委托出去。 这将允许隔离测试每个方面而没有副作用,甚至如果需要,甚至还可以从磁盘加载实际的XDocument

可以仅使用为该测试提供的必要依赖项来测试给定的方案。 这可以用来测试是否捕获到异常,或者是您在原始问题中省略的逻辑中的其他内容。

在设计代码时使用SOLID方法可以使其易于维护,其中包括单元测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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