本文整理汇总了C#中Mock.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# Mock.ToString方法的具体用法?C# Mock.ToString怎么用?C# Mock.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mock
的用法示例。
在下文中一共展示了Mock.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ActionFilter_SettingResult_ShortCircuits
// This is used as a 'common' test method for ActionFilterAttribute and Controller
public static async Task ActionFilter_SettingResult_ShortCircuits(Mock mock)
{
// Arrange
mock.As<IAsyncActionFilter>()
.Setup(f => f.OnActionExecutionAsync(
It.IsAny<ActionExecutingContext>(),
It.IsAny<ActionExecutionDelegate>()))
.CallBase();
mock.As<IActionFilter>()
.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()))
.Callback<ActionExecutingContext>(c =>
{
mock.ToString();
c.Result = new NoOpResult();
});
mock.As<IActionFilter>()
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Verifiable();
var context = CreateActionExecutingContext(mock.As<IFilter>().Object);
var next = new ActionExecutionDelegate(() => { throw null; }); // This won't run
// Act
await mock.As<IAsyncActionFilter>().Object.OnActionExecutionAsync(context, next);
// Assert
Assert.IsType<NoOpResult>(context.Result);
mock.As<IActionFilter>()
.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Never());
}
示例2: ExecuteAsync_WritesOutputWithoutBOM
public async Task ExecuteAsync_WritesOutputWithoutBOM()
{
// Arrange
var expected = new byte[] { 97, 98, 99, 100 };
var view = new Mock<IView>();
view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>()))
.Callback((ViewContext v) =>
{
view.ToString();
v.Writer.Write("abcd");
})
.Returns(Task.FromResult(0));
var context = new DefaultHttpContext();
var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;
var actionContext = new ActionContext(context,
new RouteData(),
new ActionDescriptor());
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
// Act
await ViewExecutor.ExecuteAsync(view.Object, actionContext, viewData, null, contentType: null);
// Assert
Assert.Equal(expected, memoryStream.ToArray());
Assert.Equal("text/html; charset=utf-8", context.Response.ContentType);
}
示例3: ExecuteResultAsync_UsesProvidedViewEngine
public async Task ExecuteResultAsync_UsesProvidedViewEngine()
{
// Arrange
var expected = new byte[] { 97, 98, 99, 100 };
var view = new Mock<IView>();
view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>()))
.Callback((ViewContext v) =>
{
view.ToString();
v.Writer.Write("abcd");
})
.Returns(Task.FromResult(0));
var routeDictionary = new Dictionary<string, object>();
var goodViewEngine = new Mock<IViewEngine>();
var badViewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine)))
.Returns(badViewEngine.Object);
var memoryStream = new MemoryStream();
var response = new Mock<HttpResponse>();
response.SetupGet(r => r.Body)
.Returns(memoryStream);
var context = new Mock<HttpContext>();
context.SetupGet(c => c.Response)
.Returns(response.Object);
context.SetupGet(c => c.RequestServices)
.Returns(serviceProvider.Object);
var actionContext = new ActionContext(context.Object,
new RouteData() { Values = routeDictionary },
new ActionDescriptor());
goodViewEngine.Setup(v => v.FindView(actionContext, It.IsAny<string>()))
.Returns(ViewEngineResult.Found("MyView", view.Object));
var viewResult = new ViewResult()
{
ViewEngine = goodViewEngine.Object,
};
// Act
await viewResult.ExecuteResultAsync(actionContext);
// Assert
Assert.Equal(expected, memoryStream.ToArray());
}
示例4: PartialMethods_DoesNotWrapThrownException
public void PartialMethods_DoesNotWrapThrownException(Func<IHtmlHelper, IHtmlContent> partialMethod)
{
// Arrange
var expected = new InvalidOperationException();
var helper = new Mock<IHtmlHelper>();
helper.Setup(h => h.PartialAsync("test", It.IsAny<object>(), It.IsAny<ViewDataDictionary>()))
.Callback(() =>
{
// Workaround for compilation issue with Moq.
helper.ToString();
throw expected;
});
helper.SetupGet(h => h.ViewData)
.Returns(new ViewDataDictionary(new EmptyModelMetadataProvider()));
// Act and Assert
var actual = Assert.Throws<InvalidOperationException>(() => partialMethod(helper.Object));
Assert.Same(expected, actual);
}
示例5: ExecuteAsync_SetsContentTypeAndEncoding
public async Task ExecuteAsync_SetsContentTypeAndEncoding(
MediaTypeHeaderValue contentType,
string expectedContentType,
byte[] expectedContentData)
{
// Arrange
var view = new Mock<IView>();
view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>()))
.Callback((ViewContext v) =>
{
view.ToString();
v.Writer.Write("abcd");
})
.Returns(Task.FromResult(0));
var context = new DefaultHttpContext();
var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;
var actionContext = new ActionContext(context,
new RouteData(),
new ActionDescriptor());
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
// Act
await ViewExecutor.ExecuteAsync(
view.Object,
actionContext,
viewData,
null,
new HtmlHelperOptions(),
contentType);
// Assert
Assert.Equal(expectedContentType, context.Response.ContentType);
Assert.Equal(expectedContentData, memoryStream.ToArray());
}
示例6: FindPage_UsesViewLocationExpander_ToExpandPaths
public void FindPage_UsesViewLocationExpander_ToExpandPaths(
IDictionary<string, object> routeValues,
IEnumerable<string> expectedSeeds)
{
// Arrange
var page = Mock.Of<IRazorPage>();
var pageFactory = new Mock<IRazorPageFactory>();
pageFactory.Setup(p => p.CreateInstance("expanded-path/bar-layout"))
.Returns(page)
.Verifiable();
var viewFactory = new Mock<IRazorViewFactory>(MockBehavior.Strict);
var expander = new Mock<IViewLocationExpander>();
expander.Setup(e => e.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext c) =>
{
Assert.NotNull(c.ActionContext);
c.Values["expander-key"] = expander.ToString();
})
.Verifiable();
expander.Setup(e => e.ExpandViewLocations(It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Returns((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.NotNull(c.ActionContext);
Assert.Equal(expectedSeeds, seeds);
Assert.Equal(expander.ToString(), c.Values["expander-key"]);
return new[] { "expanded-path/bar-{0}" };
})
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object, viewFactory.Object,
new[] { expander.Object });
var context = GetActionContext(routeValues);
// Act
var result = viewEngine.FindPage(context, "layout");
// Assert
Assert.Equal("layout", result.Name);
Assert.Same(page, result.Page);
Assert.Null(result.SearchedLocations);
pageFactory.Verify();
expander.Verify();
}
示例7: FindView_UsesViewLocationExpandersToLocateViews
public void FindView_UsesViewLocationExpandersToLocateViews(
IDictionary<string, object> routeValues,
IEnumerable<string> expectedSeeds)
{
// Arrange
var pageFactory = new Mock<IRazorPageFactory>();
pageFactory.Setup(p => p.CreateInstance("test-string/bar.cshtml"))
.Returns(Mock.Of<IRazorPage>())
.Verifiable();
var viewFactory = new Mock<IRazorViewFactory>();
viewFactory.Setup(p => p.GetView(It.IsAny<IRazorViewEngine>(), It.IsAny<IRazorPage>(), It.IsAny<bool>()))
.Returns(Mock.Of<IView>());
var expander1Result = new[] { "some-seed" };
var expander1 = new Mock<IViewLocationExpander>();
expander1.Setup(e => e.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext c) =>
{
Assert.NotNull(c.ActionContext);
c.Values["expander-key"] = expander1.ToString();
})
.Verifiable();
expander1.Setup(e => e.ExpandViewLocations(It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Callback((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.NotNull(c.ActionContext);
Assert.Equal(expectedSeeds, seeds);
})
.Returns(expander1Result)
.Verifiable();
var expander2 = new Mock<IViewLocationExpander>();
expander2.Setup(e => e.ExpandViewLocations(It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Callback((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.Equal(expander1Result, seeds);
})
.Returns(new[] { "test-string/{1}.cshtml" })
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object, viewFactory.Object,
new[] { expander1.Object, expander2.Object });
var context = GetActionContext(routeValues);
// Act
var result = viewEngine.FindView(context, "test-view");
// Assert
Assert.True(result.Success);
Assert.IsAssignableFrom<IView>(result.View);
pageFactory.Verify();
expander1.Verify();
expander2.Verify();
}
示例8: ProcessAsync_BindsRouteValues
public async Task ProcessAsync_BindsRouteValues()
{
// Arrange
var testViewContext = CreateViewContext();
var context = new TagHelperContext(
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var expectedAttribute = new TagHelperAttribute("asp-ROUTEE-NotRoute", "something");
var output = new TagHelperOutput(
"form",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Attributes.Add(expectedAttribute);
var generator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
generator
.Setup(mock => mock.GenerateForm(
It.IsAny<ViewContext>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<object>(),
It.IsAny<string>(),
It.IsAny<object>()))
.Callback<ViewContext, string, string, object, string, object>(
(viewContext, actionName, controllerName, routeValues, method, htmlAttributes) =>
{
// Fixes Roslyn bug with lambdas
generator.ToString();
var routeValueDictionary = (Dictionary<string, object>)routeValues;
Assert.Equal(2, routeValueDictionary.Count);
var routeValue = Assert.Single(routeValueDictionary, attr => attr.Key.Equals("val"));
Assert.Equal("hello", routeValue.Value);
routeValue = Assert.Single(routeValueDictionary, attr => attr.Key.Equals("-Name"));
Assert.Equal("Value", routeValue.Value);
})
.Returns(new TagBuilder("form"))
.Verifiable();
var formTagHelper = new FormTagHelper(generator.Object)
{
Action = "Index",
Antiforgery = false,
ViewContext = testViewContext,
RouteValues =
{
{ "val", "hello" },
{ "-Name", "Value" },
},
};
// Act & Assert
await formTagHelper.ProcessAsync(context, output);
Assert.Equal("form", output.TagName);
Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode);
var attribute = Assert.Single(output.Attributes);
Assert.Equal(expectedAttribute, attribute);
Assert.Empty(output.PreContent.GetContent());
Assert.True(output.Content.GetContent().Length == 0);
Assert.Empty(output.PostContent.GetContent());
generator.Verify();
}
示例9: InvokeAction_InvokesResultFilter_ShortCircuit
public async Task InvokeAction_InvokesResultFilter_ShortCircuit()
{
// Arrange
ResultExecutedContext context = null;
var filter1 = new Mock<IResultFilter>(MockBehavior.Strict);
filter1.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>())).Verifiable();
filter1
.Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()))
.Callback<ResultExecutedContext>(c => context = c)
.Verifiable();
var filter2 = new Mock<IResultFilter>(MockBehavior.Strict);
filter2
.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()))
.Callback<ResultExecutingContext>(c =>
{
filter2.ToString();
c.Cancel = true;
})
.Verifiable();
var filter3 = new Mock<IResultFilter>(MockBehavior.Strict);
var invoker = CreateInvoker(new IFilterMetadata[] { filter1.Object, filter2.Object, filter3.Object });
// Act
await invoker.InvokeAsync();
// Assert
filter1.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
filter1.Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
filter2.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
Assert.True(context.Canceled);
}
示例10: InvokeAction_InvokesAsyncExceptionFilter_ShortCircuit
public async Task InvokeAction_InvokesAsyncExceptionFilter_ShortCircuit()
{
// Arrange
var filter1 = new Mock<IExceptionFilter>(MockBehavior.Strict);
var filter2 = new Mock<IAsyncExceptionFilter>(MockBehavior.Strict);
filter2
.Setup(f => f.OnExceptionAsync(It.IsAny<ExceptionContext>()))
.Callback<ExceptionContext>(context =>
{
filter2.ToString();
context.Exception = null;
})
.Returns<ExceptionContext>((context) => Task.FromResult(true))
.Verifiable();
var invoker = CreateInvoker(new IFilterMetadata[] { filter1.Object, filter2.Object }, actionThrows: true);
// Act
await invoker.InvokeAsync();
// Assert
filter2.Verify(
f => f.OnExceptionAsync(It.IsAny<ExceptionContext>()),
Times.Once());
}
示例11: ResultFilter_SettingCancel_ShortCircuits
// This is used as a 'common' test method for ActionFilterAttribute and ResultFilterAttribute
public static async Task ResultFilter_SettingCancel_ShortCircuits(Mock mock)
{
// Arrange
mock.As<IAsyncResultFilter>()
.Setup(f => f.OnResultExecutionAsync(
It.IsAny<ResultExecutingContext>(),
It.IsAny<ResultExecutionDelegate>()))
.CallBase();
mock.As<IResultFilter>()
.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()))
.Callback<ResultExecutingContext>(c =>
{
mock.ToString();
c.Cancel = true;
});
mock.As<IResultFilter>()
.Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()))
.Verifiable();
var context = CreateResultExecutingContext(mock.As<IFilter>().Object);
var next = new ResultExecutionDelegate(() => { throw null; }); // This won't run
// Act
await mock.As<IAsyncResultFilter>().Object.OnResultExecutionAsync(context, next);
// Assert
Assert.True(context.Cancel);
mock.As<IResultFilter>()
.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
mock.As<IResultFilter>()
.Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Never());
}
示例12: ResultFilter_SettingResult_DoesNotShortCircuit
// This is used as a 'common' test method for ActionFilterAttribute and ResultFilterAttribute
public static async Task ResultFilter_SettingResult_DoesNotShortCircuit(Mock mock)
{
// Arrange
mock.As<IAsyncResultFilter>()
.Setup(f => f.OnResultExecutionAsync(
It.IsAny<ResultExecutingContext>(),
It.IsAny<ResultExecutionDelegate>()))
.CallBase();
mock.As<IResultFilter>()
.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()))
.Callback<ResultExecutingContext>(c =>
{
mock.ToString();
c.Result = new NoOpResult();
});
mock.As<IResultFilter>()
.Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()))
.Verifiable();
var context = CreateResultExecutingContext(mock.As<IFilter>().Object);
var next = new ResultExecutionDelegate(() => Task.FromResult(CreateResultExecutedContext(context)));
// Act
await mock.As<IAsyncResultFilter>().Object.OnResultExecutionAsync(context, next);
// Assert
Assert.False(context.Cancel);
mock.As<IResultFilter>()
.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
mock.As<IResultFilter>()
.Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
}
示例13: ProcessAsync_BindsRouteValuesFromTagHelperOutput
public async Task ProcessAsync_BindsRouteValuesFromTagHelperOutput()
{
// Arrange
var testViewContext = CreateViewContext();
var context = new TagHelperContext(
allAttributes: new Dictionary<string, object>(),
items: new Dictionary<object, object>(),
uniqueId: "test",
getChildContentAsync: () =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
var expectedAttribute = new KeyValuePair<string, object>("asp-ROUTEE-NotRoute", "something");
var output = new TagHelperOutput(
"form",
attributes: new Dictionary<string, object>()
{
{ "asp-route-val", "hello" },
{ "asp-roUte--Foo", "bar" }
});
output.Attributes.Add(expectedAttribute);
var generator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
generator
.Setup(mock => mock.GenerateForm(
It.IsAny<ViewContext>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<object>(),
It.IsAny<string>(),
It.IsAny<object>()))
.Callback<ViewContext, string, string, object, string, object>(
(viewContext, actionName, controllerName, routeValues, method, htmlAttributes) =>
{
// Fixes Roslyn bug with lambdas
generator.ToString();
var routeValueDictionary = (Dictionary<string, object>)routeValues;
Assert.Equal(2, routeValueDictionary.Count);
var routeValue = Assert.Single(routeValueDictionary, kvp => kvp.Key.Equals("val"));
Assert.Equal("hello", routeValue.Value);
routeValue = Assert.Single(routeValueDictionary, kvp => kvp.Key.Equals("-Foo"));
Assert.Equal("bar", routeValue.Value);
})
.Returns(new TagBuilder("form", new HtmlEncoder()))
.Verifiable();
var formTagHelper = new FormTagHelper
{
Action = "Index",
AntiForgery = false,
Generator = generator.Object,
ViewContext = testViewContext,
};
// Act & Assert
await formTagHelper.ProcessAsync(context, output);
Assert.Equal("form", output.TagName);
Assert.False(output.SelfClosing);
var attribute = Assert.Single(output.Attributes);
Assert.Equal(expectedAttribute, attribute);
Assert.Empty(output.PreContent.GetContent());
Assert.True(output.Content.IsEmpty);
Assert.Empty(output.PostContent.GetContent());
generator.Verify();
}
示例14: ExecuteAsync_DoesNotWriteToResponse_OnceExceptionIsThrown
public async Task ExecuteAsync_DoesNotWriteToResponse_OnceExceptionIsThrown(int writtenLength, int expectedLength)
{
// Arrange
var longString = new string('a', writtenLength);
var view = new Mock<IView>();
view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>()))
.Callback((ViewContext v) =>
{
view.ToString();
v.Writer.Write(longString);
throw new Exception();
});
var context = new DefaultHttpContext();
var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;
var actionContext = new ActionContext(context,
new RouteData(),
new ActionDescriptor());
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
// Act
await Record.ExceptionAsync(
() => ViewExecutor.ExecuteAsync(view.Object, actionContext, viewData, null, contentType: null));
// Assert
Assert.Equal(expectedLength, memoryStream.Length);
}
示例15: ExecuteResultAsync_DoesNotWriteToResponse_OnceExceptionIsThrown
public async Task ExecuteResultAsync_DoesNotWriteToResponse_OnceExceptionIsThrown(int writtenLength, int expectedLength)
{
// Arrange
var longString = new string('a', writtenLength);
var routeDictionary = new Dictionary<string, object>();
var view = new Mock<IView>();
view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>()))
.Callback((ViewContext v) =>
{
view.ToString();
v.Writer.Write(longString);
throw new Exception();
});
var viewEngine = new Mock<ICompositeViewEngine>();
viewEngine.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>()))
.Returns(ViewEngineResult.Found("MyView", view.Object));
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine)))
.Returns(viewEngine.Object);
var memoryStream = new MemoryStream();
var response = new Mock<HttpResponse>();
response.SetupGet(r => r.Body)
.Returns(memoryStream);
var context = new Mock<HttpContext>();
context.SetupGet(c => c.Response)
.Returns(response.Object);
context.SetupGet(c => c.RequestServices).Returns(serviceProvider.Object);
var actionContext = new ActionContext(context.Object,
new RouteData() { Values = routeDictionary },
new ActionDescriptor());
var viewResult = new ViewResult();
// Act
await Record.ExceptionAsync(() => viewResult.ExecuteResultAsync(actionContext));
// Assert
Assert.Equal(expectedLength, memoryStream.Length);
}