如何在NSubstitute中模拟返回对象的索引器信息

时间:2016-10-21 13:21:12

标签: c# nunit nsubstitute

我想通过对象模拟索引器属性返回。我正在使用NSubstitute进行嘲弄。我有以下情况。在示例中,我想从IFeedData.GetFeedData返回时模拟索引器属性 this [string symbolName]

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");

        }
    }

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

要模拟FeedEntity,我们需要让其所有成员virtual或提取界面。然后我们可以像这样模拟索引器:

var feedEntity = Substitute.For<IFeedEntity>();
feedEntity["ABC"] = new SymbolData(...);
// or if it is a get-only indexer:
feedEntity["ABC"].Returns(new SymbolData(...));

如果你只是想测试FeedProcessor,我们可能不需要达到那个级别的细节。我们只能替换IFeedData

[Test]
public void TestProcessing() {
    var feedData = Substitute.For<IFeedData>();
    feedData.GetFeedData("HHH").Returns(new FeedEntity(...)); 
    // Configure substitute to return a real FeedEntity. 
    // Alternatively, return a substitute IFeedEntity as described above
    var subject = new FeedProcessor(feedData);

    subject.ProcessFeedData();

    // assert correct processing  
}