2

I am new to unit test, MSTest. I get NullReferenceException.

How do I set HttpContext.Current.Server.MapPath for doing unit test?

class Account
{
    protected string accfilepath;

    public Account(){
        accfilepath=HttpContext.Current.Server.MapPath("~/files/");
    }
}

class Test
{
    [TestMethod]
    public void TestMethod()
    {
        Account ac= new Account();
    }
}
Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Urbi
  • 125
  • 1
  • 4
  • 18
  • Maybe this post will be helpful http://stackoverflow.com/questions/9624242/setting-httpcontext-current-session-in-a-unit-test – Tasos K. Aug 06 '16 at 15:22

2 Answers2

3

HttpContext.Server.MapPath would require an underlying virtual directory provider which would not exist during the unit test. Abstract the path mapping behind a service that you can mock to make the code testable.

public interface IPathProvider {
    string MapPath(string path);
}

In the production implementation of the concrete service you can make your call to map the path and retrieve the file.

public class ServerPathProvider: IPathProvider {
    public MapPath(string path) {
        return HttpContext.Current.Server.MapPath(path);
    }
}

you would inject the abstraction into your dependent class or where needed and used

class Account {
    protected string accfilepath;

    public Account(IPathProvider pathProvider) {
        accfilepath = pathProvider.MapPath("~/files/");
    }
}

Using your mocking framework of choice or a fake/test class if a mocking framework is not available,

public class FakePathProvider : IPathProvider {
    public string MapPath(string path) {
        return Path.Combine(@"C:\testproject\",path.Replace("~/",""));
    }
}

you can then test the system

[TestClass]
class Test {

    [TestMethod]
    public void TestMethod() {
        // Arrange
        IPathProvider fakePathProvider = new FakePathProvider();

        Account ac = new Account(fakePathProvider);

        // Act
        // ...other test code
    }
}

and not be coupled to HttpContext

Nkosi
  • 235,767
  • 35
  • 427
  • 472
-2

You can create another constructor that takes a path as parameter. That way you can pass a fake path for unit testing

alltej
  • 6,787
  • 10
  • 46
  • 87