使用Moq对创建了Stack
的视图模型的MVC 4操作方法进行了以下测试:
// GET: /Home/SowingAndHarvesting
public ActionResult SowingAndHarvesting()
{
// Months are used for the CSS classes
// to add to the squares and for displayal within the square.
var months = MonthHelper.GetAllMonths().ToList();
// Ordering for the squared boxes view (4 columns for the seasons)
var monthIndexOrdering = new[] { 7, 4, 1, 10,
6, 3, 0, 9,
5, 2, 11, 8 };
var displayMonthsOrdered = new Stack<MonthViewModel>();
foreach (var monthIndex in monthIndexOrdering)
{
var month = months[monthIndex];
var name = month.ToString();
var monthViewModel = new MonthViewModel(name);
displayMonthsOrdered.Push(monthViewModel);
}
var viewModel = new SowingAndHarvestingViewModel
{
// Months in the squared and information belonging to the month
OrderedMonthViewModels = displayMonthsOrdered
};
return View(viewModel);
}
MonthViewModel
就像这样(它有一些显示的属性,为简洁起见,SowingAndHarvestingViewModel
是一个包装器):
public class MonthViewModel
{
public MonthViewModel(string monthName)
{
MonthForDataAttribute = monthName.ToLower();
}
public string MonthForDataAttribute { get; set; }
}
测试如下:
[TestFixture]
public class HomeControllerTest
{
[Test]
public void Controllers_SowingAndHarvesting_DataMonthOrdering()
{
// Arrange
var expectedMonthOrdering = return new Stack<MonthViewModel>(new[]
{
new MonthViewModel("august"),
new MonthViewModel("may"),
new MonthViewModel("february"),
new MonthViewModel("november"),
new MonthViewModel("july"),
new MonthViewModel("april"),
new MonthViewModel("january"),
new MonthViewModel("october"),
new MonthViewModel("june"),
new MonthViewModel("march"),
new MonthViewModel("december"),
new MonthViewModel("september")
}); ;
var mock = new Mock<ICalendarService>();
mock.Setup(c => c.GetMonthsWithAction())
.Returns(It.IsAny<Month>);
var controller = new HomeController(mock.Object);
// Act
var result = (SowingAndHarvestingViewModel)((ViewResult)controller.SowingAndHarvesting()).Model;
// Assert
while (expectedMonthOrdering.Count != 0)
{
var expected = expectedMonthOrdering.Pop().MonthForDataAttribute;
var actual = result.OrderedMonthViewModels.Pop().MonthForDataAttribute;
Assert.AreEqual(expected, actual,
"The months in the data attributes should be in the correct order and format.");
}
}
现在,当我单独运行此测试时,它会通过。但是,当我与其他测试一起运行时,它会失败并显示消息:
System.TypeInitializationException:Moq.Mock`1的类型初始值设定项引发了异常 ----&GT; System.TypeInitializationException:Moq.Proxy.CastleProxyFactory的类型初始化程序抛出异常 ----&GT; System.NullReferenceException:未将对象引用设置为对象的实例
有谁知道为什么会这样,以及如何解决?
答案 0 :(得分:3)
如果您使用的是.Net Framework 4.6和Web API,则由于最近对Castle.Core进行了更新,您可能会遇到此错误。将Castle.Core更新到v4.2.0将导致此错误,因此请尝试将Castle.Core NuGet包滚回4.1.1版
答案 1 :(得分:1)
我正在运行Mono 3.12,如mono -V
所示。使用sudo apt-get install mono-complete
更新为Mono 4可解决此问题!