NUinit CollectionAssert 未按预期工作
我有一个视图模型类,如下所示:
public class MyViewModel
{
// Other properties......
public IEnumerable<SelectListItem> SecurityQuestions { get; set; }
}
在我的控制器中,我有以下代码:
public ViewResult Index()
{
var viewModel = new MyViewModel {SecurityQuestions = GetSecurityQuestions()};
return View(viewModel);
}
public IEnumerable<SelectListItem> GetSecurityQuestions()
{
return new SelectList(_securityQuestionService.GetAll(),
"SecurityQuestionID",
"Question");
}
我编写了一个单元测试来测试 Index 操作方法:
[Test]
public void Can_Load_View_With_Security_Questions()
{
var result = _controller.Index();
var questions = _controller.GetSecurityQuestions();
var viewModel = result.ViewData.Model as MyViewModel;
CollectionAssert.AreEqual(questions, viewModel.SecurityQuestions);
}
我期望此测试能够顺利通过。但我收到以下错误:
Expected: <System.Web.Mvc.SelectList>
But was: <System.Web.Mvc.SelectList>
为什么会发生这种情况?
I have a view model class as follows:
public class MyViewModel
{
// Other properties......
public IEnumerable<SelectListItem> SecurityQuestions { get; set; }
}
In my controller I have the following code:
public ViewResult Index()
{
var viewModel = new MyViewModel {SecurityQuestions = GetSecurityQuestions()};
return View(viewModel);
}
public IEnumerable<SelectListItem> GetSecurityQuestions()
{
return new SelectList(_securityQuestionService.GetAll(),
"SecurityQuestionID",
"Question");
}
I have written a unit test to test the Index action method:
[Test]
public void Can_Load_View_With_Security_Questions()
{
var result = _controller.Index();
var questions = _controller.GetSecurityQuestions();
var viewModel = result.ViewData.Model as MyViewModel;
CollectionAssert.AreEqual(questions, viewModel.SecurityQuestions);
}
I was expecting this test to pass without any problems. But I am getting the below error:
Expected: <System.Web.Mvc.SelectList>
But was: <System.Web.Mvc.SelectList>
Why is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么你会期待这样的事情呢?问题可能来自于您两次调用
_securityQuestionService.GetAll()
方法。第一次在控制器操作中,第二次在单元测试中,这可能是不同的实例。还有SelectList
type 不会覆盖 Equals 方法,因此您遇到的是正常行为。Why would you be expecting such a thing? The problem might come from the fact that you are calling the
_securityQuestionService.GetAll()
method twice. The first time inside the controller action and the second time inside your unit test which could different instances. Also theSelectList
type doesn't override the Equals method so what you are experiencing is normal behavior.