我有一个方法,该方法调用使用new关键字返回类对象的方法。我需要使用此返回的对象来调用方法。
public class XmlHelper
{
public Func<string,string,IParser> FunctionParser { get; set; }
public XmlHelper(IFileUtility iFileUtility)
{
fileUtility = iFileUtility;
FunctionParser = GetParser;
}`
public void ParseFiles()
{
try
{
log.Info("XmlHelper:ParseFiles:Started.");
XmlDocument doc = null;
XmlNamespaceManager nsmgr;
string[] xmlInputFiles = fileUtility.GetFiles(ConfigurationManager.AppSettings["InputPath"], "*xml");
foreach (string file in xmlInputFiles)
{
doc = new XmlDocument();
doc.Load(file);
nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("a", doc.DocumentElement.NamespaceURI);
var recipientId = doc.DocumentElement.GetElementsByTagName("RecipientID");
var datasourceType = doc.DocumentElement.SelectSingleNode("//a:TransactionInfo/a:DataContext/a:DataSourceCollection/a:DataSource/a:Type", nsmgr)?.InnerText;
if (string.IsNullOrEmpty(datasourceType))
datasourceType = doc.DocumentElement.SelectSingleNode("//a:Shipment/a:DataContext/a:DataSourceCollection/a:DataSource/a:Type", nsmgr)?.InnerText;
var transportMode = doc.DocumentElement.SelectSingleNode("//a:Shipment/a:TransportMode/a:Code", nsmgr)?.InnerText;
if (recipientId.Count <= 0 || string.IsNullOrEmpty(datasourceType))
continue;
if (recipientId[0].InnerText.Equals(Constants.RecipientID.test.ToString(), StringComparison.OrdinalIgnoreCase))
{
FunctionParser(datasourceType,transportMode).ParseFiles(doc);
}
}
}
catch (Exception exception)
{
log.Error(exception.Message + exception.InnerException);
}
}
protected IParser GetParser(string datasourceType, string transportMode)
{
IParser parser = null;
if (datasourceType.Equals(Constants.InvoiceDatasourceType, StringComparison.OrdinalIgnoreCase))
{
parser = new Parser1(new C1(new RegionalExpressEntities()), new EmailService(), new XMLUtility());
}
else if (!string.IsNullOrEmpty(transportMode) && transportMode.Equals(Constants.TransportMode.AIR.ToString(), StringComparison.OrdinalIgnoreCase) &&
datasourceType.Equals(Constants.ShipmentDatasourceType, StringComparison.OrdinalIgnoreCase))
{
parser = new Parser2(new C1(new RegionalExpressEntities()), new EmailService(), new Helper1());
}
else if (!string.IsNullOrEmpty(transportMode) && transportMode.Equals(Constants.TransportMode.SEA.ToString(), StringComparison.OrdinalIgnoreCase) &&
datasourceType.Equals(Constants.ShipmentDatasourceType, StringComparison.OrdinalIgnoreCase))
{
parser = new Parser3(new C1(new RegionalExpressEntities()), new EmailService(), new Helper1());
}
return parser;
}
}
我知道接口是编写可单元测试的代码的解决方案之一,但是我想使用Func / Actions来模拟方法 GetParser()。
我已经创建了Func的一个属性,然后为其分配了GetParser函数。但是现在我无法在测试方法中使用它。如何在单元测试中使用它?
我指的是Best way to unit test methods that call other methods inside same class。如果方法和Func是无参数的,那么我可以按照给定的链接使用它,但就我而言,func具有参数。我在这里如何使用相同的概念?