我希望学习如何正确注入来自.NET Core库的依赖项,如StreamReader和FileStream。如何注射这些?
我有一个类,它读取包含一堆人口统计数据的文件中,选择随机抽样,然后将其作为多行字符串返回给其调用方。它通过一个FileStream来访问文件的内容,然后通过一个StreamReader来读取FileStream的内容,这样我就可以操纵文本。但是,我希望使这个单元可测试。如果我需要注入一个我自己创建的类,我会为该类生成一个接口来实现并将其传递到构造函数中,但这是一个.NET Core类型,没有我可以注入的IFileStream,IStreamWriter等。注入这些内容的正确方法是什么,这样我就可以在单元测试期间用模拟代替?
namespace MyNS.Lib
{
using System.IO;
using System.Text;
using PgpCore;
/// <summary>
/// A class for PGP encrypting strings.
/// </summary>
public class EncryptUtility
{
/// <summary>
/// Initializes a new instance of the <see cref="EncryptUtility"/> class.
/// </summary>
/// <param name="sampler">The CensusSampler needed by the class.</param>
public EncryptUtility(CensusSampler sampler)
{
Sampler = sampler;
}
/// <summary>
/// Encrypts a census file.
/// </summary>
/// <param name="censusFilePath">The path to the census file.</param>
/// <param name="keyPath">The path to the public key file.</param>
/// <returns>Returns an encrypted census file.</returns>
public string EncryptCensus(string censusFilePath, string keyPath)
{
using (FileStream census = new FileStream(censusFilePath, FileMode.Open))
{
var censusSr = new StreamReader(census);
var censusText = censusSr.ReadToEnd();
return EncryptString(censusText, keyPath);
}
}
}
}
SMILET
相关分类