使用MOQ对控制器操作方法进行单元测试

时间:2015-02-23 17:37:51

标签: unit-testing moq

我有以下控制器操作方法。

[HttpPost]
    public ActionResult CreateProvider(Provider provider)
    {
        try
        {
            int providerCreationSuccessful = _repository.CreateProvider(provider);
            if (providerCreationSuccessful == 2)
                TempData["userIntimation"] = "Provider Registered Successfully";

            //return RedirectToAction("ShowTheListOfProviders");
        }
        catch (Exception Ex)
        {
            _logger.Error(Ex.Message);
            return View("Error");
        }
        return Json(new { url = Url.Action("ShowTheListOfProviders", "Provider") });
    }

我为上述方法编写了以下测试用例,正在运行

[TestMethod()]
    public void CreateProviderTest()
    {
        mockProviderRepository.Setup(provider => provider.CreateProvider(_provider)).Returns(new int());
        var providerCreationResult = _providerController.CreateProvider(_provider) as ActionResult;
        Assert.IsNotNull(providerCreationResult);
    }

从我在action方法中的代码中可以看出,我使用AJAX重定向,因此返回要重定向到的url的JSON。

现在,测试显然是失败的。我是单元测试的新手,并且想知道我需要对Testmethod做什么更新才能通过。请指导我。谢谢。

1 个答案:

答案 0 :(得分:0)

如果您想测试Json Result包含预期的URL,您可以编写如下的测试。

[TestMethod]
public void CreateProvider_Execute_EnsureJsonContainsExpectedUrl()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    var response = new Mock<HttpResponseBase>();

    context.Setup(ctx => ctx.Request).Returns(request.Object);
    context.Setup(ctx => ctx.Response).Returns(response.Object);
    request.SetupGet(x => x.ApplicationPath).Returns("/");
    request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
    response.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => x);

    context.SetupGet(x => x.Request).Returns(request.Object);
    context.SetupGet(x => x.Response).Returns(response.Object);
    RouteConfig.RegisterRoutes(new RouteCollection());

    var repoStub = new Mock<IRepository>();
    repoStub.Setup(x => x.CreateProvider(new Provider())).Returns(1);

    var sut = new HomeController(repoStub.Object, new Mock<ILogger>().Object);

    sut.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);

    var result = sut.CreateProvider(new Provider()) as JsonResult;
    var actualUrl = GetValueFromJsonResult<string>(result, "url");
    Assert.AreEqual<string>("/Provider/ShowTheListOfProviders", actualUrl);
}


private T GetValueFromJsonResult<T>(JsonResult jsonResult, string propertyName)
 {
     var property =
         jsonResult.Data.GetType().GetProperties()
                .Where(p => string.Compare(p.Name, propertyName) == 0)
                .FirstOrDefault();

     if (null == property)
                throw new ArgumentException("propertyName not found", "propertyName");
            return (T)property.GetValue(jsonResult.Data, null);
 }