我有一个类使用近似求解方程,计算近似值,然后细化近似值(二分法),冲洗并重复直到答案出现。 为了做到这一点,它需要从其他复杂类中获取各种值。它还需要在自身内部重复调用一个方法,以便在再次运行该方法之前确定如何更改猜测。我设法测试了计算方法:
protected double GRPY(double royGuess, ReductionOnYield redOnYield )
{
log.LogEnter();
double d1 = 0D;
double d2 = 0D;
double growth = 0D;
double regularPremiumInMonthm = 0D;
double termSurrenderValue = Convert.ToDouble(illus.GetCashInValue(redOnYield.Month) * GetFundStreamSplit(redOnYield, redOnYield.Month));
for (int i = 1; i <= redOnYield.Month; i++)
{
regularPremiumInMonthm = Convert.ToDouble(illus.RegularPremium.PremiumAmount * Convert.ToDecimal(GetFundStreamSplit(redOnYield, i)));
d1 = (1 + royGuess);
d2 = (redOnYield.Month - (i - 1)) / 12D;
growth = growth + Convert.ToDouble(regularPremiumInMonthm) * Math.Pow(d1, d2);
}
double gRoy = ((termSurrenderValue - growth))/termSurrenderValue;
log.LogExit();
return gRoy;
}
但是我现在想测试一下调用calculate方法的猜测新近似方法:
protected double SetNewMidPoint(double midPoint, double gStartLow, double gStartHigh, double gMidPoint, ReductionOnYield redOnYield)
{
log.LogEnter();
if ((gStartLow * gStartHigh) > 0)
{
startLow = 0.001D;
startHigh = 0.07D;
midPoint = (startHigh - startLow)/2 + startLow;
gStartLow = GRPY(startLow, redOnYield);
gStartHigh = GRPY(startHigh, redOnYield);
gMidPoint = GRPY(midPoint, redOnYield);
if((gStartLow > 0) && (gStartHigh > 0))
{
midPoint = 0.07D;
}
if ((gStartLow < 0) && (gStartHigh < 0))
{
midPoint = 0D;
}
}
if((gStartLow * gMidPoint) < 0)
{
startHigh = midPoint;
midPoint = (startHigh - startLow)/2 + startLow;
}
if((gStartLow * gMidPoint) > 0)
{
startLow = midPoint;
midPoint = (startHigh - startLow)/2 + startLow;
}
log.LogExit();
return midPoint;
}
这是测试但显然不起作用。我知道我错过了一些东西(可能是关于Rhino Mocks的重要基础)
[TestMethod()]
public void SetNewMidPointGStartLowTimesGStartHighGreaterThanZeroTest()
{
var quote = MockRepository.GenerateStub<EQuote>();
double growthRate = 0.07;
quote.Request = new Request();
var illustration = MockRepository.GenerateStub<Illustration>(quote, growthRate);
var target = MockRepository.GenerateMock<RegularPremiumReductionOnYieldCalculator_Accessor>(illustration);
double gStartLow = 0.1F;
double gStartHigh = 0.1F;
double gMidPoint = 0.1F;
double startLow = 0F;
double startHigh = 0F;
double midPoint = 0F;
var redOnYield = MockRepository.GenerateStub<ReductionOnYield>(1);
target.Stub(x => x.GRPY(0.001D, redOnYield)).Return(0.07D).Repeat.Once();
target.Stub(x => x.GRPY(0.07D, redOnYield)).Return(0.07D).Repeat.Once();
target.Stub(x => x.GRPY(midPoint, redOnYield)).Return(0).Repeat.Any();
double actual = target.SetNewMidPoint(midPoint, gStartLow, gStartHigh, gMidPoint, redOnYield);
double expected = 0.07D;
Assert.AreEqual(expected, actual);
}
答案 0 :(得分:0)
通常在编写测试时证明非常困难,这意味着您应该将您的课程分成较小的类。在您的情况下,我的第一个猜测是您的计算方法应该在一个类中,并且您的近似方法(使用计算方法的方法)应该在不同的类中。然后第二个类将使用第一个类。在测试中,您可以模拟测试类,以便您可以轻松控制计算方法将返回的内容。