// 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()); }
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(); }
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, contentType : null); // Assert Assert.Equal(expected, memoryStream.ToArray()); Assert.Equal("text/html; charset=utf-8", context.Response.ContentType); }
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, contentType: null)); // Assert Assert.Equal(expectedLength, memoryStream.Length); }
private void MockToStringTest(Mock <IParentInterface> mock) { mock.ThrowToStringException = false; string s = mock.ToString(); Assert.AreEqual(mock.Name, s); }
private static ICompositeViewEngine CreateViewEngine() { var view = new Mock <IView>(); view .Setup(v => v.RenderAsync(It.IsAny <ViewContext>())) .Callback(async(ViewContext v) => { view.ToString(); await v.Writer.WriteAsync(FormatOutput(v.ViewData.ModelExplorer)); }) .Returns(Task.FromResult(0)); var viewEngine = new Mock <ICompositeViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny <string>(), /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("MyView", Enumerable.Empty <string>())) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny <ActionContext>(), It.IsAny <string>(), /*isMainPage*/ false)) .Returns(ViewEngineResult.Found("MyView", view.Object)) .Verifiable(); return(viewEngine.Object); }
// 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()); }
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); }
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(); }
public void MockShoudReturnInformationThatObjectWasntInitialized() { var firstMock = new Mock <IUserService>(); var information = firstMock.ToString(); Assert.StartsWith("Object wasn't initialized.", information); }
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 = Mock.Of <IViewEngine>(); var badViewEngine = new Mock <ICompositeViewEngine>(MockBehavior.Strict); var serviceProvider = new Mock <IServiceProvider>(); serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine))) .Returns(badViewEngine.Object); var context = new DefaultHttpContext { RequestServices = serviceProvider.Object, }; var memoryStream = new MemoryStream(); context.Response.Body = memoryStream; var actionContext = new ActionContext(context, new RouteData { Values = routeDictionary }, new ActionDescriptor()); var result = new Mock <ViewResultBase> { CallBase = true }; result.Protected() .Setup <ViewEngineResult>("FindView", goodViewEngine, actionContext, ItExpr.IsAny <string>()) .Returns(ViewEngineResult.Found("MyView", view.Object)) .Verifiable(); result.Object.ViewEngine = goodViewEngine; // Act await result.Object.ExecuteResultAsync(actionContext); // Assert Assert.Equal(expected, memoryStream.ToArray()); result.Verify(); }
public async Task ExecuteResultAsync_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 routeDictionary = new Dictionary <string, object>(); var viewEngine = new Mock <ICompositeViewEngine>(); 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()); viewEngine.Setup(v => v.FindView(actionContext, It.IsAny <string>())) .Returns(ViewEngineResult.Found("MyView", view.Object)); var viewResult = new ViewResult(); // Act await viewResult.ExecuteResultAsync(actionContext); // Assert Assert.Equal(expected, memoryStream.ToArray()); }
public void ToString_ReturnsValueToString() { var value = Mock.Of <object>(m => m.ToString() == "x"); var instance = new Mock <EncapsulatedValueAbstract <object> >(value) { CallBase = true }.Object; Check.That(instance.ToString()).Equals(value.ToString()); }
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()); }
public void ATagWithoutAdditionalParamsReturnsTheBareTag() { var tag = Fixture.Create <string>(); var sut = new Mock <BaseCoreElement>(tag) { CallBase = true }.Object; var actual = sut.ToString(false, 0); actual.ShouldBe(string.Format(@"<{0} />", tag)); }
public void MockShouldReturnInformationMassegeViaToString() { var firstMock = new Mock <IUserService>(); firstMock.Setup(x => x.MethodReturnsInt()).Returns(20); firstMock.Object.SimplestMethod(); firstMock.Object.SimplestMethod(); var information = firstMock.ToString(); Assert.StartsWith("Object was initialized.", information); }
public void ATagWithAnInnerTagReturnsTheTagAndTheNested() { var tag = Fixture.Create <string>(); var inner = Fixture.Create <BaseCoreElement>(); var sut = new Mock <BaseCoreElement>(tag, inner) { CallBase = true }.Object; sut.ToString().ShouldBe(string.Format(@"<{0}>{1}</{0}>", tag, inner)); }
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); }
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 = Mock.Of <ICompositeViewEngine>(); var serviceProvider = new Mock <IServiceProvider>(); serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine))) .Returns(viewEngine); var context = new DefaultHttpContext { RequestServices = serviceProvider.Object, }; var memoryStream = new MemoryStream(); context.Response.Body = memoryStream; var actionContext = new ActionContext(context, new RouteData { Values = routeDictionary }, new ActionDescriptor()); var result = new Mock <ViewResultBase> { CallBase = true }; result.Protected() .Setup <ViewEngineResult>("FindView", viewEngine, actionContext, ItExpr.IsAny <string>()) .Returns(ViewEngineResult.Found("MyView", view.Object)) .Verifiable(); // Act await Record.ExceptionAsync(() => result.Object.ExecuteResultAsync(actionContext)); // Assert Assert.Equal(expectedLength, memoryStream.Length); }
public void ToString_ShouldReturnPassedDataAListOfLectures() { var course = new Course("Name", 2, new DateTime(2010, 10, 10), new DateTime(2011, 11, 11)); var mockLecture = new Mock <ILecture>(); var anotherMockLecture = new Mock <ILecture>(); course.Lectures.Add(mockLecture.Object); course.Lectures.Add(anotherMockLecture.Object); Assert.That(course.ToString().Contains(mockLecture.ToString())); Assert.That(course.ToString().Contains(anotherMockLecture.ToString())); }
public void ATagWithAnAttributeReturnsTheTagAndTheAttribute() { var tag = Fixture.Create <string>(); var attrName = Fixture.Create <string>(); var attrVal = Fixture.Create <string>(); var sut = new Mock <BaseCoreElement>(tag, new Tuple <string, string>(attrName, attrVal)) { CallBase = true }.Object; sut.ToString().ShouldBe(string.Format(@"<{0} {1}=""{2}"" />", tag, attrName, attrVal)); }
public void AHash_StringRepresentation_ReturnsHashHexadecimalRepresentation_Value() { var inputStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4 }); var hash = new Mock <StreamHash>( inputStream, Mock.Of <THashAlgorithm>()) { CallBase = true }.Object; var expectedRepresentation = HashStringRepresentation.Process(hash); Check.That(hash.ToString()).Equals(expectedRepresentation); }
public void CamlTagAttributeAndInnerCgReturnsTheTagWithAttributeAndTheNestedCg() { var tag = Fixture.Create <string>(); var attrName = Fixture.Create <string>(); var attrVal = Fixture.Create <string>(); var inner = Fixture.Create <BaseCoreElement>(); var attrs = new[] { new Tuple <string, string>(attrName, attrVal) }; var inners = new[] { inner }; var sut = new Mock <BaseCoreElement>(tag, attrs, inners) { CallBase = true }.Object; sut.ToString().ShouldBe(string.Format(@"<{0} {1}=""{2}"">{3}</{0}>", tag, attrName, attrVal, inner)); }
public void TwoNestedTagWithFormattingReturnAStringWithFormatting() { var one = new Mock <BaseCoreElement>("One") { CallBase = true }.Object; var two = new Mock <BaseCoreElement>("Two") { CallBase = true }.Object; one.Childs.Add(two); var actual = one.ToString(true); actual.ShouldBe(string.Format("<One>{0} <Two />{0}</One>{0}", Environment.NewLine)); }
public void NestedElementsReturnsTheNestedTags() { var outerTag = Fixture.Create <string>(); var innerTag = Fixture.Create <string>(); var sut = new Mock <BaseCoreElement>(outerTag) { CallBase = true }.Object; sut.Childs.Add(new Mock <BaseCoreElement>(innerTag) { CallBase = true }.Object); sut.ToString().ShouldBe(string.Format(@"<{0}><{1} /></{0}>", outerTag, innerTag)); }
public void TwoNestedTagWithoutFormattingReturnAStringWithoutFormatting() { var one = new Mock <BaseCoreElement>("One") { CallBase = true }.Object; var two = new Mock <BaseCoreElement>("Two") { CallBase = true }.Object; one.Childs.Add(two); var actual = one.ToString(false); actual.ShouldBe("<One><Two /></One>"); }
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); }
private static ICompositeViewEngine CreateViewEngine() { var view = new Mock <IView>(); view .Setup(v => v.RenderAsync(It.IsAny <ViewContext>())) .Callback(async(ViewContext v) => { view.ToString(); await v.Writer.WriteAsync(FormatOutput(v.ViewData.ModelMetadata)); }) .Returns(Task.FromResult(0)); var viewEngine = new Mock <ICompositeViewEngine>(); viewEngine .Setup(v => v.FindPartialView(It.IsAny <ActionContext>(), It.IsAny <string>())) .Returns(ViewEngineResult.Found("MyView", view.Object)); return(viewEngine.Object); }
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); }
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()); }
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()); }
// 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()); }
// 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()); }
// 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()); }
public async Task ProcessAsync_BindsRouteValues() { // Arrange var testViewContext = CreateViewContext(); var context = new TagHelperContext( tagName: "form", 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 = Assert.IsType <RouteValueDictionary>(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(); }
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(); }
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(); }
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); }
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()); }
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); }
// 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()); }
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); }
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(); }
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(); }
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(); }