他是使用 NUnit 和 Moq 测试的 MVC 4 的默认 WebAPI 项目的 Web API 控制器的示例单元测试。
//ValuesController.cs in GetPostExample project
using System.Collections.Generic;
using System.Web.Http;
namespace GetPostExample.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post(string value)
{
}
// PUT api/values/5
public void Put(int id, string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
//AGetPostValuesControllerShould.cs in GetPostExampleTest project
using System.Web.Http.Controllers;
using GetPostExample.Controllers;
using Moq;
using NUnit.Framework;
namespace GetPostExampleTest
{
[TestFixture]
public class AGetPostValuesControllerShould
{
private Mock<HttpControllerContext> _controllerContext;
[SetUp]
public void Init()
{
_controllerContext = new Mock<HttpControllerContext>();
_controllerContext.SetupAllProperties();
}
[Test]
public void WhenAGetRequestIsCalledToValuesontrollerItShouldReturnAnArrayOfValues()
{
var expected = new[] {"value1", "value2"};
var valuesController = new ValuesController {ControllerContext = _controllerContext.Object};
var result = valuesController.Get();
Assert.That(result, Is.EqualTo(expected));
}
}
}