私はこれを次のようにしました:
[TestFixture]
public class CountriesApiTests
{
private const string BaseEndPoint = "http://x/api/countries";
[Test]
public void Test_CountryApiController_ReturnsListOfEntities_ForGet()
{
var repoMock = new Mock<ISimpleRepo<Country>>();
ObjectFactory.Initialize(x => x.For<ISimpleRepo<Country>>().Use(repoMock.Object));
repoMock.Setup(x => x.GetAll()).Returns(new List<Country>
{
new Country {Name = "UK"},
new Country {Name = "US"}
}.AsQueryable);
var client = new TestClient(BaseEndPoint);
var countries = client.Get<IEnumerable<CountryModel>>();
Assert.That(countries.Count(), Is.EqualTo(2));
}
}
TestClient コード:
public class TestClient
{
protected readonly HttpClient _httpClient;
protected readonly string _endpoint;
public HttpStatusCode LastStatusCode { get; set; }
public TestClient(string endpoint)
{
_endpoint = endpoint;
var config = new HttpConfiguration();
config.ServiceResolver.SetResolver(new WebApiDependencyResolver());
config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
_httpClient = new HttpClient(new HttpServer(config));
}
public T Get<T>() where T : class
{
var response = _httpClient.GetAsync(_endpoint).Result;
response.EnsureSuccessStatusCode(); // need this to throw exception to unit test
return response.Content.ReadAsAsync<T>().Result;
}
}