Jam*_*mes 6 .net c# unit-testing class-design stream
我有一个输出简单报告文件的类.它从XML文件中读取一些记录ID号:每个用于查找存储在数据库中的匹配记录.然后它将每个记录的详细信息写入CSV文件.
我想知道 - 组织它的最佳方法是什么,以便它易于测试,但遵循封装原则?我认为最好避免与文件系统交互,除非绝对必要,所以我正在处理Stream对象.单元测试时,我可以使用部分模拟对象来覆盖读取或写入文件的位.
我也不确定何时/何处处理流而不使单元测试变得棘手.看起来我可能不得不将流暴露给单元测试.
我的项目使用NHibernate进行数据访问,使用Spring .NET进行依赖注入,使用Rhino.Mocks进行单元测试.
目前我有类似的东西:
public class ReportBiz
{
//Access to repository, populated by Spring
internal ICardRequestDAO CardRequestData { get;set;}
//This normally returns a FileStream containing data from the XML file. When testing this is overridden by using a Rhino.Mocks partial mock and returns a MemoryStream
internal virtual Stream GetSourceStream()
{
//Load file and return a Stream
...
}
//This normally returns a FileStream where CSV data is saved. When testing this is overridden by using a Rhino.Mocks partial mock and returns a MemoryStream
internal virtual Stream GetOutputStream()
{
//Create file where CSV data gets saved and return a Stream
...
}
public void CreateReportFile()
{
Stream sourceStream = GetSourceStream();
...
//Create an XmlDocument instance using the stream
//For each XML element, get the corresponding record from the database
//Add record data to CSV stream
...
}
}
Run Code Online (Sandbox Code Playgroud)
使用某种自定义工厂或其他东西并将流传递给构造函数会更好吗?但是,如果涉及一些业务逻辑,例如文件名是根据查询结果确定的呢?
或者整个文件访问的东西毕竟不是问题?
如果我遗漏了一些明显的东西,请道歉.我会很感激任何建议.
最简单的方法是使文件访问模拟,同时保持对可支配资源生命周期的控制是在StreamFactory您的类中注入:
public class ReportBiz {
private IStreamFactory streamFactory;
public ReportBiz(IStreamFactory streamFactory) {
this.streamFactory = streamFactory
}
public void CreateReportFile() {
using(Stream stream = this.streamFactory.CreateStream()) {
// perform the important work!
}
}
}
Run Code Online (Sandbox Code Playgroud)
当涉及更多的业务逻辑时,您的工厂方法可能会更复杂,但不是很多:
public void CreateReportFile() {
string sourcePath = this.otherComponent.GetReportPath();
using(Stream stream = this.streamFactory.CreateStream(sourcePath)) {
// perform the important work!
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3719 次 |
| 最近记录: |