我希望通过对象模拟索引器属性的返回值。我使用NSubstitute进行模拟。我有以下场景。在示例中,我想要模拟索引器属性this[string symbolName],同时从IFeedData.GetFeedData返回。
public class FeedEntity
{
private SymbolData _symbolData;
public string Symbol { get; set; }
public SymbolData this[string symbolName]
{
get //Search Data into Actual Feed and returns relevent data for Symbol
{
if (_symbolData != null)
{
_symbolData = new SymbolData//Just Created For Sample Purpose
{
TraderName = "TestTrader",
BrokerName = "TestBroker"
};
}
return _symbolData;
}
set
{
_symbolData = value;
}
}
}
public class SymbolData
{
public string TraderName { get; set; }
public string BrokerName { get; set; }
}
public interface IFeedData
{
FeedEntity GetFeedData(string symbolName);
}
public class FeedClass : IFeedData
{
public FeedEntity GetFeedData(string symbolName)
{
return new FeedEntity
{
Symbol = "TestSymbol"
};
}
}
引用 IFeedData 的主要类 -
public class FeedProcesser
{
private IFeedData _feedService = new FeedClass();
public FeedProcesser(IFeedData feedService)
{
_feedService = feedService;
}
public void ProcessFeedData(string symbol)
{
var feedRespnse= _feedService.GetFeedData(symbol);
//do feed processing logic based on Trader and Broker Information
}
}
单元测试类 -
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var iFeedData = Substitute.For<FeedClass>();
iFeedData.GetFeedData(Arg.Any<string>()).Returns(x => new FeedEntity() { Symbol = "HHH" });
var processer = new FeedProcesser(iFeedData);
processer.ProcessFeedData("HHH");
}
}
需要帮助!感激不尽!