我想测试一个以 ViewModel 作为参数的辅助方法。我遇到的问题是测试似乎需要我实例化并分配我的 ViewModel 使用的所有模型。在我下面给出的示例中,这没什么大不了的,因为只有几个,但在我正在处理的实际 VM 中却有很多。有没有其他方法可以做到这一点,所以我不必创建和分配每个对象?
用于说明目的的示例代码...
模型
public class Meal
{
public int MealID { get; set; }
public string Title { get; set; }
public decimal Cost { get; set; }
}
public class Beverage
{
public int BeverageID { get; set; }
public string Title { get; set; }
public decimal Cost { get; set; }
}
public class Desert
{
public int DesertID { get; set; }
public string Title { get; set; }
public decimal Cost { get; set; }
}
视图模型
public class DinnerViewModel
{
public Meal Meal { get; set; }
public Beverage Beverage { get; set; }
public Desert Desert { get; set; }
public decimal SalesTax { get; set; }
public bool SeniorDiscount { get; set; }
}
帮手
public class Calculator
{
public decimal Total(DinnerViewModel dvm)
{
decimal subtotal = dvm.Meal.Cost + dvm.Beverage.Cost + dvm.Desert.Cost;
if (dvm.SeniorDiscount)
{
subtotal = subtotal - (subtotal * 0.1M);
}
return subtotal + (subtotal * dvm.SalesTax);
}
}
考试
[TestMethod]
public void CalculatorReturnsCorrectTotalForNonSenior()
{
DinnerViewModel dvm = new DinnerViewModel();
dvm.Meal.Cost = 7M;
dvm.Beverage.Cost = 1M;
dvm.Desert.Cost = 2M;
dvm.SalesTax = 0.08M;
dvm.SeniorDiscount = false;
Calculator calc = new Calculator();
decimal expected = 10.80M;
decimal actual = calc.Total(dvm);
Assert.AreEqual(expected, actual, "The actual value does not match the expected value.");
}
这会导致“NullReferenceException”错误。正如我所说,我可以创建和分配必要的对象......
[...]
Meal meal = new Meal();
dvm.Meal = meal;
dvm.Meal.Cost = 7M;
[...]
...而且,一旦它们都完成了,测试就会成功——但这似乎是在更大的 VM 上做的大量工作,我觉得我必须做一些事情来让这更容易。