如何对应用了属性的控制器方法进行单元测试?

时间:2018-02-08 07:14:59

标签: asp.net-mvc unit-testing asp.net-web-api

我根据需要为Web API的身份验证创建自己的自定义属性。 当我测试方法成功测试但方法属性未经测试以及我如何单元测试Web API自定义属性时,我还为测试Web API创建了单元测试项目。

API代码:

[HttpGet]
[AuthenticateTokenFilter]
public dynamic CheckUserSeession(string UserID, string AccessID)
{
    try
    {                   
        TestAPIModel users = new TestAPIModel();

        users.Name = "RAM";
        users.ID = "12";
        users.UserName = "M";

        var loAPIResponse = new APIResultItem<TestAPIModel> { Data = users, HttpStatusCode = HttpStatusCode.OK, ErrorGUID = null };
        return loAPIResponse;
    }
    catch (Exception Ex)
    {
        throw Ex;
    }
} 

[AuthenticateTokenFilter]是我的自定义属性,代码为:

 public class AuthenticateTokenFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext foAction)
        {
            if (!CheckUserAccessID(foAction.ActionArguments))
            {
                UserLoginResponseModel loResponseModel = new UserLoginResponseModel();
                loResponseModel.Message = "AuthenticationFailed";
                if (foAction.ActionArguments != null)
                {
                    if (foAction.ActionArguments.ContainsKey("AccessID") && !string.IsNullOrEmpty(foAction.ActionArguments.ContainsKey("AccessID").ToString()))
                        loResponseModel.AccessId = foAction.ActionArguments["AccessID"].ToString();
                    if (foAction.ActionArguments.ContainsKey("UserID") && !string.IsNullOrEmpty(foAction.ActionArguments.ContainsKey("UserID").ToString()))
                        loResponseModel.UserId = foAction.ActionArguments["UserID"].ToString();
                }
                var loInvalidUserSession = new APIResultItem<UserLoginResponseModel> { Data = loResponseModel, HttpStatusCode = HttpStatusCode.Unauthorized, ErrorGUID = null };
                foAction.Response = foAction.Request.CreateResponse(loInvalidUserSession);
            }
        }  



    public bool CheckUserAccessID(Dictionary<string, object> foActionArguments)
    {
        bool lbIsValidUserSession = false;
        try
        {
            if (foActionArguments.ContainsKey("AccessID") && foActionArguments.ContainsKey("UserID"))
            {
                CommonBAL loCommonBAL = new CommonBAL();
                lbIsValidUserSession = loCommonBAL.CheckUserSession(Convert.ToString(foActionArguments["AccessID"]), Convert.ToString(foActionArguments["UserID"]));
            }
        }
        catch (Exception)
        {
            throw;
        }
        return lbIsValidUserSession;
    }
}

测试代码:

[TestMethod()]
[AuthenticateTokenFilter]
public void TestUserSessionSuccess()
{
    TestAPIModel loResponseModel = new TestAPIModel();
    var loExpectedAPIResponse = new APIResultItem<TestAPIModel> { Data = loResponseModel, HttpStatusCode = HttpStatusCode.OK, ErrorGUID = null };

    TestControllerBuilder loTestBuilder = new TestControllerBuilder();
    TNHDefaultWebAPIController loAPIController = new TNHDefaultWebAPIController();
    string lsUserId = "BA893C8B-6DC1-428A-BEF4-0C86389CD58F", lsAccessId = "D95DB230-2A80-4E33-992B-AC46F97DAAB7";
    var loActualResult = (APIResultItem<TestAPIModel>)loAPIController.CheckUserSeession(lsUserId, lsAccessId);
    Assert.AreEqual(loExpectedAPIResponse.HttpStatusCode, loActualResult.HttpStatusCode);
}

如何测试AuthenticateTokenFilter属性?

1 个答案:

答案 0 :(得分:2)

我建议您查看代码的结构并进行清理。除此之外,如果要测试属性的功能,则需要创建属性的实例,并提供执行该操作所需的必要依赖项。

例如

[TestClass]
public class AuthenticateTokenFilterTests {
    [TestMethod]
    public void AuthenticateTokenFilter_UnAuthorized() {
        //Arrange
        var actionContext = new HttpActionContext() {
            //...you basically need to set the necessay properties used by the attribute here
        };
        var subject = new AuthenticateTokenFilter();
        //Act
        subject.OnActionExecuting(actionContext);

        //Assert
        Assert.AreEqual(HttpStatusCode.Unauthorized, actionContext.Response.StatusCode);
    }
}

该属性似乎大量使用actionContext.ActionArguments,因此创建一个包含所需值的字典并将其用于测试。可以修改它们以涵盖属性的不同测试用例。