如何使用Rhino Mocks模拟此值

时间:2010-04-15 16:56:36

标签: rhino-mocks

这是我试图测试的方法:

public override void CalculateReductionOnYield()
    {
        log.LogEnter();
        if (illus.RpFundStreams.Count <= 0)
        {
            throw new InvalidDataException("No regular premium fund streams which are required in order to calculate reduction on yield");
        }
        // Add the individual ReductionOnYield classes to the collection.)
        foreach (RegularPremiumFundStream fs in illus.RpFundStreams)
        {
            foreach (int i in ReductionOnYieldMonths)
            {
                ReductionOnYield roy = new ReductionOnYield(i);
                roy.FundStream = fs;
                ReductionsOnYield.Add(roy);
            }
            foreach (ReductionOnYield redOnYield in ReductionsOnYield)
            {
                if (redOnYield.Month == 0 || illus.RegularPremiumInPlanCurrency == 0M)
                {
                    redOnYield.Reduction = 0M;
                }
                else
                {
                    double[] regPremiums = new double[redOnYield.Month + 1];
                    for (int i = 1; i <= redOnYield.Month; i++)
                    {
                        regPremiums[i - 1] = Convert.ToDouble(-1*redOnYield.FundStream.FundStreamMonths[i].ValRegularPremium);
                    }
                    regPremiums[redOnYield.Month] = Convert.ToDouble(redOnYield.FundStream.GetFundStreamValue(redOnYield.Month));
                    redOnYield.Reduction = Convert.ToDecimal(Math.Pow((1 + Financial.IRR(ref regPremiums, 0.001D)), 12) - 1);
                }
            }
        }

如何模拟所有必需的类来测试redOnYield.Reduction的值以确保它正常工作?

e.g。我如何模拟redOnYield.FundStream.GetFundStreamValue(redOnYield.Month)和redOnYield.FundStream.FundStreamMonths [i] .ValRegularPremium?

这是有效的测试吗?或者我是以错误的方式解决这个问题?

2 个答案:

答案 0 :(得分:0)

没有关于你的对象的更多信息很难说,但你需要类似的东西:

var fundStream = MockRepository.GenerateStub<TFundStream>();
fundStream.Stub(f => f.GetFundStreamValue(60)).Return(220000M);

var redOnYeild = MockRepository.GenerateStub<TRedOnYeild>();
redOnYeild.Stub(r => r.FundStream).Return(fundStream);

答案 1 :(得分:0)

redOnYield是迭代ReductionsOnYield返回的对象。我不知道这是从哪里来的。如果我们假设它是一个虚拟属性,那么你将需要创建一个模拟ReductionOnYield对象的集合并存根ReductionsOnYield来返回你的模拟集合(或者,为了更容易测试,让CalculateReductionOnYield接受一个I​​Enumerable并对该集合进行操作)。

一旦你解决了ReductionsOnYield问题,安德鲁对剔除属性的回应将帮助你实现目标。当然,这假设FundStream是虚拟的(因此它可以被模拟/存根)以及RegularPremiumFundStream的GetFundStreamValue和FundStreamMonths。