所以我有一个使用 HttpClient 来调用 web 服务的控制器,如下所示:
public class DemoController : Controller
{
HttpClient client;
string baseUrl = "http://localhost:90/webservice";
public DemoController()
{
client = new HttpClient
{
BaseAddress = new Uri(baseUrl)
};
}
// GET: DemoInfo
public async Task<ActionResult> Index()
{
HttpResponseMessage response = await client.GetAsync(baseUrl + "vehicle/menu/year");
string content = "";
MenuItems result = null;
if (response.IsSuccessStatusCode)
{
content = await response.Content.ReadAsStringAsync();
result = (MenuItems)new XmlSerializer(typeof(MenuItems)).Deserialize(new StringReader(content));
}
return View("Index", result);
}
}
我对这个动作的单元测试如下:
[TestMethod]
public async Task Test_Index()
{
// Arrange
DemoController controller = new DemoController();
// Act
var result = await controller.Index();
ViewResult viewResult = (ViewResult) result;
// Assert
Assert.AreEqual("Index", viewResult.ViewName);
Assert.IsNotNull(viewResult.Model);
}
所以很明显,我想避免每次运行测试时都调用 Web 服务。我是否会选择像 Unity 这样的 IoC 容器,以便将 HttpClient 注入控制器中?对于我想要实现的目标来说,这是否太过分了?我知道有很多历史,人们通过这个github issue在单元测试中努力正确模拟 httpclient 。如果您能深入了解如何编写控制器以在仍可测试的情况下进行服务调用,我们将不胜感激。
慕工程0101907
BIG阳
相关分类