gpt4 book ai didi

c# - 如何对 ViewModel 使用方法进行单元测试?

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:47 24 4
gpt4 key购买 nike

我想测试一个以 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; }
}

ViewModel

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; }
}

helper

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 上做的大量工作,我觉得我必须做些什么来使这更容易。

最佳答案

您会看到 NullReferenceException,因为当您实例化它时,Meal、Beverage 和 Desert 实例没有分配给 DinnerViewModel 的相应属性。因此,所有这些属性都是 null。在访问这些属性之前,您应该创建并分配新对象。您可以使用 View 模型的构造函数:

public class DinnerViewModel
{
public DinnerViewModel()
{
Meal = new Meal();
Beverage = new Beverage();
Desert = new Desert();
}

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; }
}

我还喜欢创建一些返回测试 stub 的辅助方法。它消除了重复并使您的测试清晰:

private DinnerViewModel CreateTenDollarsDinner()
{
return new DinnerViewModel {
Meal = new Meal { Cost = 7M },
Beverage = new Beverage { Cost = 1M },
Desert = new Desert { Cost = 2M },
SalesTax = 0.08M,
SeniorDiscount = false
};
}

[TestMethod]
public void CalculatorReturnsCorrectTotalForNonSenior()
{
DinnerViewModel dvm = CreateTenDollarsDinner();
Calculator calc = new Calculator();
Assert.AreEqual(10.80M, calc.Total(dvm));
}

关于c# - 如何对 ViewModel 使用方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19569890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com