微软文件在使用Moq对APIC控制器方法进行单位测试方面有一些很好的例子。 下面是你所领导的控制者可能认为什么的基本例子。
www.un.org/Depts/DGACM/index_spanish.htm
public class EmployeeController : ApiController
{
IEmployeeRepository _repository;
public EmployeeController(IEmployeeRepository repository)
{
_repository = repository;
}
[HttpGet]
public IHttpActionResult Get(int id)
{
Employee employee = _repository.GetById(id);
if (employee == null)
{
return NotFound();
}
return Ok(employee);
}
[HttpPost]
public IHttpActionResult Post(Employee employee)
{
_repository.Add(employee);
return CreatedAtRoute("DefaultApi", new { id = employee.Id }, employee);
}
[HttpDelete]
public IHttpActionResult Delete(int id)
{
_repository.Delete(id);
return Ok();
}
[HttpPut]
public IHttpActionResult Put(Employee employee)
{
// Do some work (not shown).
return Content(HttpStatusCode.Accepted, employee);
}
}
这里最大的变化是,将“你”类别中的usage与数据库互动,从 娱乐/>。 您的榜样是,在您的APIC方法中,你正在即时推出一个新的<代码>EmployeeDetails。 最好把任何附属物作为接口注入你的控制器,以便能够在你的测试中轻易加以改动。
此处为核查<代码>的单位试验 雇员/编码 方法回归类型和数据:
[TestMethod]
public void GetReturnsEmployeeWithSameId()
{
// Arrange
var mockRepository = new Mock<IEmployeeRepository>();
mockRepository.Setup(x => x.GetById(42))
.Returns(new Employee { Id = 42 });
var controller = new EmployeeController(mockRepository.Object);
// Act
IHttpActionResult actionResult = controller.Get(42);
var contentResult = actionResult as OkNegotiatedContentResult<Employee>;
// Assert
Assert.IsNotNull(contentResult);
Assert.IsNotNull(contentResult.Content);
Assert.AreEqual(42, contentResult.Content.Id);
}
其他测试例子,包括其余的APIC方法,均列入相关文件。
作为what的测试,一般建议验证:
- The action returns the correct type of response.
- Invalid parameters return the correct error response.
- The action calls the correct method on the repository or service layer.
- If the response includes a domain model, verify the model type.