NSubstitute使用ActionName模拟HttpActionDescriptor

时间:2015-09-15 21:33:18

标签: c# asp.net unit-testing nsubstitute

我正在为我的Web API控制器编写的 AuthorizeAttribute 类编写一些测试。我试图模拟我需要能够在我的类中设置以下变量的所有内容 AuthorizeAttributeTotalAccess

  1. actionName = filterContext.ActionDescriptor.ActionName;
  2. controllerName = filterContext.ControllerContext.ControllerDescriptor.ControllerName;
  3. claimsPrincipal = HttpContext.Current.User as ClaimsPrincipal;
  4. 注意我没有和HttpContext.Current结婚,如果有另一个上下文,那么thaat会一直拥有它,请告诉我。

    到目前为止,我的测试看起来像:

    var request = $.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
        if (data != 0) {
            message = data;
        } 
        return message;
    });
    
    // HERE I HAD TO SAVE THIS VALUE TO A NEW VARIABLE; 
    // $('#new_variable').val(); WAS NOT ACCESSIBLE OTHERWISE IN THE ROUTINE THAT FOLLOWED:
    var nv = $('#new_variable').val();
    
    // HERE IT WAS IRRELEVANT WHAT ARGUMENT WENT INTO function(),
    // EXCEPT IT COULD *NOT* BE message; YOU HAD SUGGESTED msg, WHICH WAS IMMATERIAL, IT TURNED OUT
    request.then(function() {
    
        // HERE I *HAD* TO USE message, NOT THE GENERIC msg THAT YOU HAD PASSED INTO THE FUNCTION:
        if (message != '') {
            alert(message);
        } else {
    
            // THE ORIGINAL FORM HERE WOULDN'T WORK, AS $('#new_variable').val() WAS INACCESSIBLE IN THE FUNCTION:
            //var newKeyword = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + $('#new_variable').val() + '" checked /> ' + $('#new_variable').val() + '</label>';
    
            // THIS, HOWEVER, WORKED...USING nv IN PLACE OF $('#new_variable').val();
            var newVariable = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + nv + '" checked /> ' + nv + '</label>';
    
            $('#checkboxes').append(newVariable);
        }
    });
    

    我错过了什么?

    同样,我如何:

    1. 设置 ActionName 以使其在要测试的类中可用?
    2. 设置 HttpContext.Current 以便我可以看到用户?

1 个答案:

答案 0 :(得分:2)

  

设置ActionName,使其在要测试的类中可用吗?

我不是NSubstitute的专家(阅读:我从未使用它),但由于你的HttpActionDescriptor是存根/模拟,你应该能够存根返回值:

actionDescriptor.ActionName.Return("BLAH");

根据NSubstitute's documentation,您知道如何处理财产的返回值。

  

设置HttpContext.Current以便我可以看到用户?

HttpContext.Current有一个setter,所以你应该可以将它设置为假上下文。 Other Stack Overflow answers演示了如何执行此操作。