在尝试测试 ASP.Net MVC 控制器/动作时,我很难将头绕在单元测试模式上。
使用以下代码,我正在尝试为该ShowPerson()
方法编写一个测试:
public class PersonController : Controller
{
private IDataAccessBlock _dab;
public PersonController()
: this(new DataAccessBlock())
{ }
public PersonController(IDataAccessBlock dab)
{
_dab = dab;
}
public ActionResult ShowPerson(PersonRequestViewModel personRequest)
{
var person = GetPersonViewModel(personRequest);
return View("Person", person);
}
private PersonViewModel GetPersonViewModel(PersonRequestViewModel personRequest)
{
var personService = new CommonDomainService.PersonService(_dab);
var dt = personService.GetPersonInfo(personRequest.Id);
var person = new PersonViewModel();
if (dt.Rows.Count == 1)
{
person.FirstName = dt.Rows[0]r["FIRSTNAME"]);
person.LastName = dt.Rows[0]["LASTNAME"];
}
return person;
}
}
我正在使用的测试(使用 nUnit 和 Moq):
[Test]
public void ShowPerson_Action_Should_Return_Person_View()
{
// Arrange
string expected = "Person";
Mock<PersonRequestViewModel> personRequestViewModelMock = new Mock<PersonRequestViewModel>();
personRequestViewModelMock.SetupProperty(f => f.Id, 123456);
Mock<IDataAccessBlock> mockDab = new Mock<IDataAccessBlock>();
PersonController personController = new PersonController(mockDab.Object);
// Act
ViewResult result = personController.ShowPerson(personRequestViewModelMock.Object) as ViewResult;
// Assert
personRequestViewModelMock.Verify();
result.Should().Not.Be.Null();
if (result != null) Assert.AreEqual(expected, result.ViewName, "Unexpected view name");
}
一切似乎都很好,直到if (dt.Rows.Count == 1)
遇到线路。我得到一个“对象引用未设置为对象的实例”。
我认为以下两行的编写方式一定有些时髦:
var personService = new CommonDomainService.PersonService(_dab);
var dt = personService.GetPersonInfo(personRequest.Id);
但我不知道从这里去哪里。我有很多看起来像这样的代码。我做错了什么,还是有实际的方法来测试它?
感谢您的任何帮助或指点。