我有一个输出简单报告文件的类。它从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
...
}
}
它会更好使用某种自定义的工厂或东西和流传入构造?但是如果涉及到一些商业逻辑,如何呢?文件名是根据查询结果确定的?
或者是整个文件访问的东西不是问题?
道歉,如果我失去了明显的东西。我会很感激任何建议。
我需要问:你的XML是做什么的?它是否只包含指向数据库记录的密钥列表? – 2010-02-11 16:46:02
除了数据库密钥外,它还包含我需要的三个与记录相关的其他字段。这些也被用在报告中。 – James 2010-02-11 16:52:55
相关:http://stackoverflow.com/questions/129036/unit-testing-code-with-a-file-system-dependency – 2010-02-11 16:58:44