Mocking HttpContext.server.MapPath in ASP.NET unit testing

前端 未结 3 1026
抹茶落季
抹茶落季 2021-02-04 21:29

I have working in unit testing in ASP.Net web application, now I have accessing my constructor in the model file to test which has Server.MapPath code for uploading my XMLfile,

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 22:05

    How already answered, you should decouple your system

    public class NugetPlatformModel
      {
        public bool IsHavingLicense { get; set; }
        public List PlatformProduct = new List();
        public NugetPlatformModel(IPlatformProductProvider provider)
        {
          var xmldoc = new XmlDocument();
          //System.Web.HttpContext.Current.Server.MapPath(@"~\Content\PlatformProducts.xml")
          xmldoc.Load(provider.Filepath);
        }
    
        public interface IPlatformProductProvider
        {
          string Filepath { get; }
        }
    
        public class PlatformProductProvider: IPlatformProductProvider
        {
          string _filepath;
          public string Filepath
          {
            get { return _filepath; }
            set { _filepath = value;}
          }
    
          public PlatformProductProvider(string path)
          {
            _filepath = path;
          }
        }
    
      }
    

    And your test could be:

    [Test]
        public void Account_UnlicensedCustomerIdentity_IsStudioLicenseAndIshavinglicenseFalse()
        {
          //Arrange
          // using Moq
          //var mock = new Mock();
          //IPlatformProductProvider provider = mock.Object;
          //provider.Filepath = "pippo.xml";
          // otherwise
                var provider = new PlatformProductProvider("pippo.xml");
    
          //Act
          NugetPlatformModel nugetPlatformModel = new NugetPlatformModel(provider);
    
          //Assert
          AssertEquals(false, nugetPlatformModel.IsHavingLicense);
    
        }
    

提交回复
热议问题