c# - 单元测试动态加载代码

标签 c# unit-testing reflection

我正在阅读并发现此代码作为问题的答案

public List<T> LoadPlugin<T>(string directory)
{
    Type interfaceType = typeof(T);
    List<T> implementations = new List<T>();

    //TODO: perform checks to ensure type is valid

    foreach (var file in System.IO.Directory.GetFiles(directory))
    {
        //TODO: add proper file handling here and limit files to check
        //try/catch added in place of ensure files are not .dll
        try
        {
            foreach (var type in System.Reflection.Assembly.LoadFile(file).GetTypes())
            {
                if (interfaceType.IsAssignableFrom(type) && interfaceType != type)
                { 
                    //found class that implements interface
                    //TODO: perform additional checks to ensure any
                    //requirements not specified in interface
                    //ex: ensure type is a class, check for default constructor, etc
                    T instance = (T)Activator.CreateInstance(type);
                    implementations.Add(instance);
                }
            }
        }
        catch { }
    }

    return implementations;
}

这让我想知道单元测试此代码的最佳方法是什么?

最佳答案

通过这种方式重构:

public List<T> LoadPlugin<T>(Type[] types)
{
    Type interfaceType = typeof(T);
    List<T> implementations = new List<T>();

    //TODO: perform checks to ensure type is valid
    try
    {
        foreach (var type in types)
        {
            if (interfaceType.IsAssignableFrom(type) && interfaceType != type)
            { 
                //found class that implements interface
                //TODO: perform additional checks to ensure any
                //requirements not specified in interface
                //ex: ensure type is a class, check for default constructor, etc
                T instance = (T)Activator.CreateInstance(type);
                implementations.Add(instance);
            }
        }
    }
    catch { }

    return implementations;
}

关于c# - 单元测试动态加载代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1174258/

相关文章:

C#.Net 4.5 属性网格 : how to hide Properties

unit-testing - 单元测试有时会失败,有时会通过

java - 单元测试仅在由 maven 运行时失败

java - 如何获取用于函数及其类的注释类型的所有注释属性?

c# - 从 .NET Core 2.1 升级到 3.1 后,当我的应用程序在 E2E 测试中启动时找不到 View

c# - SELECT 过滤器查询中的日期格式

java - Hibernate - 在预加载事件上使字段 transient

java - 在没有容器的情况下解决 EJB 依赖关系

c# - 键盘事件只作用一次

python - Mock : Tracking all Calls. Shell 与程序不一致