[英]how to mock ActionExecutingContext and ActionExecutionDelegate to unit test "OnActionExecutionAsync" method using MOQ framework
[英]How to mock ActionExecutingContext with moq
我正在嘗試為OnActionExecutionAsync
模擬ActionExecutingContext
。
我需要為以下代碼編寫單元測試用例。
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
var controllerInfo = actionExecutingcontext.ActionDescriptor as ControllerActionDescriptor;
MyCustomAttribute[] myCustomAttribute = (MyCustomAttribute[])controllerInfo.MethodInfo.GetCustomAttributes(typeof(MyCustomAttribute), inherit: true);
}
我發現了如何用Moq模擬ActionExecutingContext? 有用,但沒有說明如何模擬methodInfo
和GetCustomAttributes
。
最近,我在嘗試模擬ActionDescriptor.FilterDescriptors
遇到了類似的問題。 由於您使用的是MethodInfo,因此您需要解決的方法與我稍有不同。 沒有Moq,這對我有用。 歸結為獲取MethodInfo實例,無論它是真正的方法,具有要測試的相同屬性的偽類/方法,還是模擬的MethodInfo。
private static ActionExecutingContext CreateActionExecutingContextTest()
{
Type t = typeof(TestClass);
var activator = new ViewDataDictionaryControllerPropertyActivator(new EmptyModelMetadataProvider());
var actionContext = new ActionContext(
new DefaultHttpContext(),
new RouteData(),
new ControllerActionDescriptor()
{
// Either Mock MethodInfo, feed in a fake class that has the attribute you want to test, or just feed in
MethodInfo = t.GetMethod(nameof(TestClass.TestMethod))
});
var controllerContext = new ControllerContext(actionContext);
var controller = new TestController()
{
ControllerContext = controllerContext
};
activator.Activate(controllerContext, controller);
return new ActionExecutingContext(
actionContext,
new List<IFilterMetadata>(),
new Dictionary<string, object>(),
controller);
}
public class TestClass
{
[MyCustomAttribute]
public void TestMethod()
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.