如何为
编写单元测试public ActionResult Details()
{
EmployeeDTO employee = this.EmployeeService.GetLoggedInEmployee();
EmployeeModel model = assembler.ToEmployeeModel(employee);
model.Title = GetEmployeeNameTitle(employee);
model.Controller = "LoanProcessor";
model.SelectedTab = MainNavTabs.LoanProcessor;
return View(model);
}
我不知道如何解决它。
答案 0 :(得分:2)
为了使您的代码可测试,您应该将依赖项注入控制器(如果您将依赖项传递给控制器,或者直接实例化它们,则从这段代码中不清楚)。此外,您应该让您的控制器依赖于抽象(最好是接口),而不是具体的实现。
EmployeeService应实现此接口:
public interface IEmployeeService
{
EmployeeDTO GetLoggedInEmployee();
// other methods of service
}
然后你根据抽象来制作你的控制器(这里只显示一个依赖关系样本):
public class FooController : Controller
{
private IEmployeeService _employeeService;
public FooController(IEmployeeService employeeService)
{
_employeeService = employeeService;
}
}
现在您可以模拟依赖项并开始为控制器编写测试(使用NUnit和Moq的示例):
[Test]
public void ShouldProvideEmployeeDetails()
{
// Arrange
EmployeeDTO bob = new EmployeDTO("Bob", 42);
Mock<IEmployeeService> employeeService = new Mock<IEmployeeService>();
employeeService.Setup(s = s.GetLoggedInEmployee()).Returns(bob);
FooController controller = new FooController(employeeService.Object);
// Act
var result = controller.Details() as ViewResult;
// Assert
EmployeeModel model = result.ViewData.Model;
Assert.That(model.Title, Is.EqualTo("Bob"));
Assert.That(model.Controller, Is.EqualTo("LoanProcessor"));
}
然后编写代码以通过此测试。 您可以阅读有关TDD here的更多信息。