How to mock application path when unit testing Web App

后端 未结 6 1271
囚心锁ツ
囚心锁ツ 2021-01-04 12:35

I am testing code in a MVC HTML helper that throws an error when trying to get the application path:

//appropriate code that uses System.IO.Path to get direc         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 13:14

    As an alternative to mocking built-in .net classes, you can

    public interface IPathProvider
    {
        string GetAbsolutePath(string path);
    }
    
    public class PathProvider : IPathProvider
    {
        private readonly HttpServerUtilityBase _server;
    
        public PathProvider(HttpServerUtilityBase server)
        {
            _server = server;
        }
    
        public string GetAbsolutePath(string path)
        {
            return _server.MapPath(path);
        }
    }
    

    Use the above class to get absolute paths.

    And for For unit testing you can mock and inject an implementation of IPathProvider that would work in the unit testing environment.

    --UPDATED CODE

提交回复
热议问题