嗨,我在创建单元测试时将 Moq 与 Autofac 一起使用。我有一个场景,我的 SUT 多个类型的实例取决于构造函数参数。我想起订这些实例。我有一个接口ISpanRecord:
interface ISpanRecord
{
RecordType RecordType { get; }
string RecordId { get; set; }
string RecordText { get; set; }
ISpanRecord ParentRecord { get; set; }
List<ISpanRecord> Children { get; }
}
我有另一个接口IRecordTypeFactory ,它基于RecordType(它是一个枚举)提供一个新的ISpanRecord
interface IRecordTypeFactory
{
ISpanRecord GetNewSpanRecord(RecordType recordType);
}
SUT SpanParser类使用上述接口
internal class SpanParser : ISpanParser
{
// Private Vars
private ISpanRecord _spanFile;
private readonly IRecordTypeFactory _factory;
private readonly ISpanFileReader _fileReader;
//Constructor
public SpanParser(ISpanFileReader fileReader)
{
_fileReader = fileReader;
_spanFile = Container.Resolve<ISpanRecord>(TypedParameter.From(RecordType.CmeSpanFile),
TypedParameter.From((List<SpanRecordAttribute>)null));
_factory = Container.Resolve<IRecordTypeFactory>(TypedParameter.From(_fileReader.PublisherConfiguration));
}
// Method under test
public SpanRiskDataSetEntity ParseFile()
{
string currRecord = string.Empty;
try
{
var treeLookUp = Container.Resolve<ITreeLookUp>(TypedParameter.From(_spanFile),
TypedParameter.From(_fileReader.PublisherConfiguration));
IList<string> filterLines = _fileReader.SpanFileLines;
ISpanRecord currentRecord;
ISpanRecord previousRecord = _spanFile;
List<string> spanRecords;
foreach (var newRecord in filterLines)
{
currRecord = newRecord;
//check if we got multiple type of records in a single line.
spanRecords = _fileReader.PublisherConfiguration.GetMultipleRecordsText(newRecord);
if (spanRecords == null)
continue;
foreach (var recordText in spanRecords)
{
RecordType recordType = _fileReader.PublisherConfiguration.GetRecordType(recordText);
currentRecord = _factory.GetNewSpanRecord(recordType);
// some more logic
GetPreviousRecord(ref previousRecord, currentRecord);
}
}
// private method
return GetSpanRiskDataSet();
}
catch (OperationCanceledException operationCanceledException)
{
// log
throw;
}
}
在上面的类中,在测试的时候,我想 根据RecordType获取ISpanRecord的多个对象。就像是:
mockFactory.Setup(fc=> fc.GetNewSpanRecord(It.IsAny<RecordType>).Returns(// an ISpanRecord object on the basis of Recordtype)
由于上述设置将在循环中进行验证,因此我想设置多个案例。请让我知道可以解决什么问题,或者指出可以解决的问题。
问候