locked
Question on Testing with XUnit RRS feed

  • Question

  • User-793197488 posted

    I have the following Tag Helper Class:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.Mvc.Routing;
    using Microsoft.AspNetCore.Mvc.ViewFeatures;
    using Microsoft.AspNetCore.Razor.TagHelpers;
    using Microsoft.EntityFrameworkCore.Internal;
    using SportStore1.Models.ViewModels;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace SportStore1.Infrastructure
    {
        [HtmlTargetElement("div", Attributes = "page-model")]
        public class PageLinkTagHelper:TagHelper
        {
           
            public IUrlHelperFactory urlFactory;
    
            public PageLinkTagHelper(IUrlHelperFactory urlFactory)
            {
                this.urlFactory = urlFactory;
            }
    
            [ViewContext]
            [HtmlAttributeNotBound]
            public ViewContext Context { get; set; }
    
            public PagingInfo PageModel { get; set; }
    
            public string PageClass { get; set; }
    
            public string PageAction { get; set; }
    
            public bool PageClassEnabled { get; set; }
    
            public string PageClassNormal { get; set; }
    
            public string PageClassSelected { get; set; }
    
            public int PageSize = 2;
    
            public TagBuilder tag, tag1, tag2;
    
            public int Start = 0;
    
            public List<TagBuilder> tagList = new List<TagBuilder>();
    
            [HtmlAttributeName(DictionaryAttributePrefix = "page-url-")]
            public Dictionary<string, object> PageUrlValues { get; set; } = new Dictionary<string, object>();
    
            public override void Process(TagHelperContext context, TagHelperOutput output)
            {
                //  base.Process(context, output);
    
                IUrlHelper urlHelper = urlFactory.GetUrlHelper((ActionContext)Context);
    
                TagBuilder result = new TagBuilder("div");
    
                tag1 = new TagBuilder("a");
                tag1.InnerHtml.AppendHtml("&laquo;");
                tag1.AddCssClass("btn");
    
                tag2 = new TagBuilder("a");
                tag2.InnerHtml.AppendHtml("&raquo;");
                tag2.AddCssClass("btn");
    
                if ((PageModel.CurrentPage < 0) || (PageModel.CurrentPage > PageModel.TotalPages))
                {
                    PageModel.CurrentPage = 1;
                }
    
                for (int i = 1; i <= PageModel.TotalPages; i++)
                {
                    if (PageModel.CurrentPage != 1)
                    {
                        tag1.Attributes["href"] = urlHelper.Action(PageAction, new { productPage = PageModel.CurrentPage - 1 });
                        tag1.Attributes.Remove("disabled");
                    }
                    else
                    {
                            tag1.MergeAttribute("disabled", "disabled");      
                    }
    
                    if (PageModel.CurrentPage == PageModel.TotalPages)
                    {
                            tag2.MergeAttribute("disabled","disabled");
                    }
                    else
                    {
                        tag2.Attributes.Remove("disabled");
                        tag2.Attributes["href"] = urlHelper.Action(PageAction, new { productPage = PageModel.CurrentPage + 1 });
                    }
    
                    tag = new TagBuilder("a");
    
                    PageUrlValues["productPage"] = i;
                    tag.Attributes["href"] = urlHelper.Action(PageAction, PageUrlValues );
                   
                    if (PageClassEnabled == true)
                    {
                        tag.AddCssClass(PageClass);
                        tag.AddCssClass(i == PageModel.CurrentPage ? PageClassSelected : PageClassNormal);
                    }
    
                    tag.InnerHtml.Append(i.ToString());
                    tagList.Add(tag);
                }
    
    
                List<TagBuilder> listTag1 = new List<TagBuilder>();
    
                if (PageModel.CurrentPage % PageSize == 0)
                {
                    Start = (PageModel.CurrentPage - PageSize);
                }
                else
                {
                    Start = (PageModel.CurrentPage - 1);
                    if (PageModel.CurrentPage == PageModel.TotalPages)
                    {
                        PageSize =  1;
                    }
                }
    
                listTag1 = tagList.GetRange(Start, PageSize);
                result.InnerHtml.AppendHtml(tag1);
    
                foreach (var r in listTag1)
                {
                    result.InnerHtml.AppendHtml(r);
                }
    
                result.InnerHtml.AppendHtml(tag2);
    
                output.Content.AppendHtml(result);
            }
        }
    }
    

    And the following Test:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Routing;
    using Microsoft.AspNetCore.Razor.TagHelpers;
    using Moq;
    using SportStore1.Infrastructure;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading.Tasks;
    using Xunit;
    
    namespace SportStore1.Tests
    {
        public class PageLinkTagHelperTests
        {
            [Fact]
            public void Can_Generate_Page_links()
            {   
                //Arrange
                var urlHelper = new Mock<IUrlHelper>();
                urlHelper.SetupSequence(f => f.Action(It.IsAny<UrlActionContext>())).Returns("Test/Page1").Returns("Test/Page2").Returns("Test/Page3");
                var urlHelperFactory = new Mock<IUrlHelperFactory>();
                urlHelperFactory.Setup(x => x.GetUrlHelper(It.IsAny<ActionContext>())).Returns(urlHelper.Object);
                PageLinkTagHelper helper = new PageLinkTagHelper(urlHelperFactory.Object)
                {
                    PageModel = new Models.ViewModels.PagingInfo
                    {
                        CurrentPage = 2,
                        TotalItems = 28,
                        ItemsPerPage = 10,
                    },
                    PageAction = "Test",
                    PageSize = 2,
                };
    
                TagHelperContext ctx = new TagHelperContext("", new TagHelperAttributeList(), new Dictionary<object, object>(), "");
    
                var content = new Mock<TagHelperContent>();
    
                TagHelperOutput output = new TagHelperOutput("div", new TagHelperAttributeList(), (cache, encoder) => Task.FromResult(content.Object));
    
    
                //Act            
                helper.Process(ctx, output);
                
                //Assert
                Assert.Equal(@"<div><a class=""btn"" href=""Test/Page1"">&laquo;</a><a href=""Test/Page1"">1</a>"+@"<a href=""Test/Page2"">2</a><a class=""btn"" href=""Test/Page3"">&raquo;</a></div>", output.Content.GetContent());
            }
        }
    }
    

    Which is failed. Any suggestion?

    Monday, July 29, 2019 8:12 AM

All replies

  • User1120430333 posted

    You can debug a unit test with the Visual Debugger and using the  MSTest test harness to host the test, debugging  line by line,  set breakpoints, use Quickwatch and the whole nine yards. I like using Resharper. myself another well known test harness.

    You're trying to do an Assert on a given output, and you need to find out why the output is not passing the Assert, by debugging the unit test and finding out why.

    You're at the 'red' right now. It's up to you to make the test pass, becuase it is you that is the one that is supposed to know the code functionality of the code being tested and  what the unit test is about, so debug it.

    https://www.codecademy.com/articles/tdd-red-green-refactor

    Monday, July 29, 2019 8:34 AM