-1

I am planning to write unit test for a web api function which is using a line of code to load XML file using Server.MapPath

While running from UnitTest project same returns null to me .

One solution to this issue is pass filename to the function from the controller So i can use Context.Current,Server.MapPath while running the web api project and while running from unit test i can use a hardcoded file path,

Is there any other way so that i can use the same line of code for both UnitTest and actual Web api endpoint call

Sebastian
  • 4,625
  • 17
  • 76
  • 145
  • `Server.MapPath` would require an underlying virtual directory provider which would not exist during the unit test. Abstract the file content retrieval behind a service that you can mock to make the code testable. In the implementation of the concrete service you can make your call to map the path and retrieve the file. In unit test you can mock the service to return what ever data you want for the test. – Nkosi May 30 '16 at 12:43

1 Answers1

0

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

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

In the 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);
    }
}

In unit test you can mock the service to return what ever data you want for the test.

Here is an example with Moq

//Arrange
var path = "~/resources/file.xml";
var expected = "My/Hard/Coded/File/Path/File.xml";
public mock = new Mock<IPathMapper>();
mock.Setup(m => m.MapPath(path)).Returns(expected);
IPathMapper mapper = mock.Object.
IMyFIleLoader loader = new MyFIleLoader(mapper);

//Act
var actual = loader.Load(path);

//Assert
mock.Verify(m => m.MapPath(path));
//...other code removed for brevity

And here is an example using a fake/test class

public class TestPathProvider : IPathProvider {
    public string MapPath(string path) {
        return Path.Combine(@"C:\project\",path);
    }
}

Reference Unit testing for Server.MapPath

Community
  • 1
  • 1
Nkosi
  • 235,767
  • 35
  • 427
  • 472