小编Mic*_*man的帖子

如何使用.Net IO类创建可测试代码?

我想创建单元可测试的代码来模拟对.Net System.IO类的调用,所以我可以真正进行单元测试,而不是依赖于文件系统.我正在使用SystemWrapper类来包装BCL类.

我试图找一个简单的例子来查看文件是否存在.

我遇到的问题是在类中注入依赖项不起作用,因为实例化依赖项(通过StructureMap)需要知道要传递的构造函数参数,这在当时是不可用的,也没有默认构造函数.

示例代码:

// don't want to create dependency here like so
//IFileInfoWrap fileInfoWrap = new FileInfoWrap(filename);

// using service locator (anti-pattern?!) since it can't be 
// injected in this class
var fileInfoWrap = ObjectFactory.GetInstance<IFileInfoWrap>(
    new ExplicitArguments(new Dictionary<string, object>
    {
        {"fileName", filename}
    }));

Console.WriteLine("File exists? {0}",  fileInfoWrap.Exists); 
Run Code Online (Sandbox Code Playgroud)

我不喜欢的是没有注入依赖项,ObjectFactory不应该在这里(但我没有看到其他创建方法).ExplicitArguments使它变得混乱,参数名称是一个魔术字符串.

让我开始工作StructureMap配置类需要知道我要使用哪个构造函数(我刚开始使用StructureMap所以这可能不是正确的设置方式):

ObjectFactory.Initialize(x =>
{
    x.Scan(scan =>
    {
        scan.AssembliesFromPath(".");
        scan.RegisterConcreteTypesAgainstTheFirstInterface();
        scan.WithDefaultConventions();
    });

    // use the correct constructor (string instead of FileInfo)
    x.SelectConstructor(() => new FileInfoWrap(null as string)); …
Run Code Online (Sandbox Code Playgroud)

c# tdd dependency-injection inversion-of-control base-class-library

7
推荐指数
1
解决办法
961
查看次数