I'm adding some unit tests for my ASP.NET Core Web API, and I'm wondering whether to unit test the controllers directly or through an HTTP client. Directly would look roughly like this:
[TestMethod]
public async Task GetGroups_Succeeds()
{
var controller = new GroupsController(
_groupsLoggerMock.Object,
_uowRunnerMock.Object,
_repoFactoryMock.Object
);
var groups = await controller.GetGroups();
Assert.IsNotNull(groups);
}
... whereas through an HTTP client would look roughly like this:
[TestMethod]
public void GetGroups_Succeeds()
{
HttpClient.Execute();
dynamic obj = JsonConvert.DeserializeObject<dynamic>(HttpClient.ResponseContent);
Assert.AreEqual(200, HttpClient.ResponseStatusCode);
Assert.AreEqual("OK", HttpClient.ResponseStatusMsg);
string groupid = obj[0].id;
string name = obj[0].name;
string usercount = obj[0].userCount;
string participantsjson = obj[0].participantsJson;
Assert.IsNotNull(name);
Assert.IsNotNull(usercount);
Assert.IsNotNull(participantsjson);
}
Searching online, it looks like both ways of testing an API seem to be used, but I'm wondering what the best practice is. The second method seems a bit better because it naively tests the actual JSON response from the Web API without knowing the actual response object type, but it's more difficult to inject mock repositories this way - the tests would have to connect to a separate local Web API server that itself was somehow configured to use mock objects... I think?
Edit: TL;DR
The conclusion you should do both because each test serves a different purpose.
Answer:
This is a good question, one I often ask myself.
First, you must look at the purpose of a unit test and the purpose of an integration test.
Unit Test :
Unit tests involve testing a part of an app in isolation from its
infrastructure and dependencies. When unit testing controller logic,
only the contents of a single action are tested, not the behaviour of
its dependencies or of the framework itself.
Things like filters, routing, and model binding will not work.
Integration Test :
Integration tests ensure that an app's components function correctly
at a level that includes the app's supporting infrastructures, such as
the database, file system, and network. ASP.NET Core supports
integration tests using a unit test framework with a test web host and
an in-memory test server.
Things like filters, routing, and model binding will work.
“Best practice” should be thought of as “Has value and makes sense”.
You should ask yourself Is there any value in writing the test, or am I just creating this test for the sake of writing a test?
Let's say your GetGroups() method looks like this.
[HttpGet]
[Authorize]
public async Task<ActionResult<Group>> GetGroups()
{
var groups = await _repository.ListAllAsync();
return Ok(groups);
}
There is no value in writing a unit test for it! because what you are doing is testing a mocked implementation of _repository! So what is the point of that?!
The method has no logic and the repository is only going to be exactly what you mocked it to be, nothing in the method suggests otherwise.
The Repository will have its own set of separate unit tests where you will cover the implementation of the repository methods.
Now let's say your GetGroups() method is more than just a wrapper for the _repository and has some logic in it.
[HttpGet]
[Authorize]
public async Task<ActionResult<Group>> GetGroups()
{
List<Group> groups;
if (HttpContext.User.IsInRole("Admin"))
groups = await _repository.FindByExpressionAsync(g => g.IsAdminGroup == true);
else
groups = await _repository.FindByExpressionAsync(g => g.IsAdminGroup == false);
//maybe some other logic that could determine a response with a different outcome...
return Ok(groups);
}
Now there is value in writing a unit test for the GetGroups() method because the outcome could change depending on the mocked HttpContext.User value.
Attributes like [Authorize] or [ServiceFilter(….)] will not be triggered in a unit test.
.
Writing integration tests is almost always worth it because you want to test what the process will do when it forms part of an actual application/system/process.
Ask yourself, is this being used by the application/system?
If yes, write an integration test because the outcome depends on a combination of circumstances and criteria.
Now even if your GetGroups() method is just a wrapper like in the first implementation, the _repository will point to an actual datastore, nothing is mocked!
So now, not only does the test cover the fact that the datastore has data (or not), it also relies on an actual connection being made, HttpContext being set up properly and whether serialisation of the information works as expected.
Things like filters, routing, and model binding will also work.
So if you had an attribute on your GetGroups() method, for example [Authorize] or [ServiceFilter(….)], it will be triggered as expected.
I use xUnit for testing so for a unit test on a controller I use this.
Controller Unit Test:
public class MyEntityControllerShould
{
private MyEntityController InitializeController(AppDbContext appDbContext)
{
var _controller = new MyEntityController (null, new MyEntityRepository(appDbContext));
var httpContext = new DefaultHttpContext();
var context = new ControllerContext(new ActionContext(httpContext, new RouteData(), new ActionDescriptor()));
_controller.ControllerContext = context;
return _controller;
}
[Fact]
public async Task Get_All_MyEntity_Records()
{
// Arrange
var _AppDbContext = AppDbContextMocker.GetAppDbContext(nameof(Get_All_MeetUp_Records));
var _controller = InitializeController(_AppDbContext);
//Act
var all = await _controller.GetAllValidEntities();
//Assert
Assert.True(all.Value.Count() > 0);
//clean up otherwise the other test will complain about key tracking.
await _AppDbContext.DisposeAsync();
}
}
The Context mocker used for unit testing.
public class AppDbContextMocker
{
/// <summary>
/// Get an In memory version of the app db context with some seeded data
/// </summary>
/// <param name="dbName"></param>
/// <returns></returns>
public static AppDbContext GetAppDbContext(string dbName)
{
//set up the options to use for this dbcontext
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(dbName)
.Options;
var dbContext = new AppDbContext(options);
dbContext.SeedAppDbContext();
return dbContext;
}
}
The Seed extension.
public static class AppDbContextExtensions
{
public static void SeedAppDbContext(this AppDbContext appDbContext)
{
var myEnt = new MyEntity()
{
Id = 1,
SomeValue = "ABCD",
}
appDbContext.MyENtities.Add(myEnt);
//add more seed records etc....
appDbContext.SaveChanges();
//detach everything
foreach (var entity in appDbContext.ChangeTracker.Entries())
{
entity.State = EntityState.Detached;
}
}
}
and for Integration Testing: (this is some code from a tutorial, but I can't remember where I saw it, either youtube or Pluralsight)
setup for the TestFixture
public class TestFixture<TStatup> : IDisposable
{
/// <summary>
/// Get the application project path where the startup assembly lives
/// </summary>
string GetProjectPath(string projectRelativePath, Assembly startupAssembly)
{
var projectName = startupAssembly.GetName().Name;
var applicationBaseBath = AppContext.BaseDirectory;
var directoryInfo = new DirectoryInfo(applicationBaseBath);
do
{
directoryInfo = directoryInfo.Parent;
var projectDirectoryInfo = new DirectoryInfo(Path.Combine(directoryInfo.FullName, projectRelativePath));
if (projectDirectoryInfo.Exists)
{
if (new FileInfo(Path.Combine(projectDirectoryInfo.FullName, projectName, $"{projectName}.csproj")).Exists)
return Path.Combine(projectDirectoryInfo.FullName, projectName);
}
} while (directoryInfo.Parent != null);
throw new Exception($"Project root could not be located using application root {applicationBaseBath}");
}
/// <summary>
/// The temporary test server that will be used to host the controllers
/// </summary>
private TestServer _server;
/// <summary>
/// The client used to send information to the service host server
/// </summary>
public HttpClient HttpClient { get; }
public TestFixture() : this(Path.Combine(""))
{ }
protected TestFixture(string relativeTargetProjectParentDirectory)
{
var startupAssembly = typeof(TStatup).GetTypeInfo().Assembly;
var contentRoot = GetProjectPath(relativeTargetProjectParentDirectory, startupAssembly);
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath(contentRoot)
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Development.json");
var webHostBuilder = new WebHostBuilder()
.UseContentRoot(contentRoot)
.ConfigureServices(InitializeServices)
.UseConfiguration(configurationBuilder.Build())
.UseEnvironment("Development")
.UseStartup(typeof(TStatup));
//create test instance of the server
_server = new TestServer(webHostBuilder);
//configure client
HttpClient = _server.CreateClient();
HttpClient.BaseAddress = new Uri("http://localhost:5005");
HttpClient.DefaultRequestHeaders.Accept.Clear();
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
/// <summary>
/// Initialize the services so that it matches the services used in the main API project
/// </summary>
protected virtual void InitializeServices(IServiceCollection services)
{
var startupAsembly = typeof(TStatup).GetTypeInfo().Assembly;
var manager = new ApplicationPartManager
{
ApplicationParts = {
new AssemblyPart(startupAsembly)
},
FeatureProviders = {
new ControllerFeatureProvider()
}
};
services.AddSingleton(manager);
}
/// <summary>
/// Dispose the Client and the Server
/// </summary>
public void Dispose()
{
HttpClient.Dispose();
_server.Dispose();
_ctx.Dispose();
}
AppDbContext _ctx = null;
public void SeedDataToContext()
{
if (_ctx == null)
{
_ctx = _server.Services.GetService<AppDbContext>();
if (_ctx != null)
_ctx.SeedAppDbContext();
}
}
}
and use it like this in the integration test.
public class MyEntityControllerShould : IClassFixture<TestFixture<MyEntityApp.Api.Startup>>
{
private HttpClient _HttpClient;
private const string _BaseRequestUri = "/api/myentities";
public MyEntityControllerShould(TestFixture<MyEntityApp.Api.Startup> fixture)
{
_HttpClient = fixture.HttpClient;
fixture.SeedDataToContext();
}
[Fact]
public async Task Get_GetAllValidEntities()
{
//arrange
var request = _BaseRequestUri;
//act
var response = await _HttpClient.GetAsync(request);
//assert
response.EnsureSuccessStatusCode(); //if exception is not thrown all is good
//convert the response content to expected result and test response
var result = await ContentHelper.ContentTo<IEnumerable<MyEntities>>(response.Content);
Assert.NotNull(result);
}
}
Added Edit:
In conclusion, you should do both, because each test serves a different purpose.
Looking at the other answers you will see that the consensus is to do both.
TL;DR
Is it best practice to test [...] directly or through an HTTP client?
Not "or" but "and". If you serious about best practices of testing - you need both tests.
First test is a unit test. But the second one is an integration test.
There is a common consensus (test pyramid) that you need more unit tests comparing to the number of integration tests. But you need both.
There are many reasons why you should prefer unit tests over integration tests, most of them boil down to the fact that unit test are small (in all senses) and integration tests - aren't. But the main 4 are:
Locality
When your unit test fails, usually, just from it's name you can figure out the place where the bug is. When integration test becomes red, you can't say right away where is the issue. Maybe it's in the controller.GetGroups or it's in the HttpClient, or there is some issue with the network.
Also, when you introduce a bug in your code it's quite possible that only one of unit tests will become red, while with integration tests there are more chances that more than one of them will fail.
Stability
With a small project which you can test on you local box you probably won't notice it. But on a big project with distributed infrastructure you will see blinking tests all the time. And that will become a problem. At some point you can find yourself not trusting test results anymore.
Speed
With a small project with a small number of tests you won't notice it. But on a bit project it will become a problem. (Network delays, IO delays, initialization, cleanup, etc., etc.)
Simplicity
You've noticed it yourself.
But that not always true. If you code is poorly structured, then it's easier to write integration tests. And that's one more reason why you should prefer unit tests. In some way they force you to write more modular code (and I'm not taking about Dependency Injection).
But also keep in mind that best practices are almost always about big projects. If your project is small, and will stay small, there are a big chance that you'll be better off with strictly opposite decisions.
Write more tests. (Again, that means - both). Become better at writing tests. Delete them latter.
Practice makes perfect.
If we limit the scope of discussion to Controller vs HttpClient testing comparison, I would say that it is better to use HttpClient. Because if you write tests for your controllers, you're already writing integration tests already and there is almost no point to write "weaker" integration tests while you can write stronger ones that is more realistic and also superset of the weaker ones.
For example, you can see from your own example that both of your test are testing exactly the same functionality. The different is that the latter one cover more area of testing -- JSON response, or can be something else like HTTP header you want to test. If you write the latter test, you don't need the first test at all.
I understand the pain of how to inject mocked dependencies. This requires more effort comparing to testing controller directly. However, .NET Core already provides a good set of tools to help you on that. You can setup the test host inside the test itself, configure it and get HttpClient from it. Then you can use that HttpClient for your testing purpose.
The other concern is that it is quite a tedious task to craft HttpClient's request for each test. Anyway, Refit can help you a lot on this. Refit's declarative syntax is quite easy to understand (and maintain eventually). While I would also recommend Refit for all remote API calls, it is also suitable for ASP.NET Core integration testing.
Combining all solutions available, I don't see why you should limit to controller test while you can go for more "real" integration test with only some little more effort.
I never have liked mocking in that as applications mature the effort spent on mocking can make for a ton of effort.
I like exercising endpoints by direct Http calls. Today there are fantastic tools like Cypress which allow the client requests to be intercepted and altered. The power of this feature along with easy Browser based GUI interaction blurs traditional test definitions because one test in Cypress can be all of these types Unit, Functional, Integration and E2E.
If an endpoint is bullet proof then error injection becomes impossible from outside. But even errors from within are easy to simulate. Run the same Cypress tests with Db down. Or inject intermittent network issue simulation from Cypress. This is mocking issues externally which is closer to a prod environment.
When doing unit test, it is important to know what are you going to test and write the tests based on your requirements. However, the second test, might looks like an integration test instead of an unit test, but I do not care to this point now!
Between your tests, I would recommend you to use the second option, because in the second unit test, you are testing your WebApi, as an WebApi, not as a class. For example suppose that you have a class with a method named X(). So how likely is it to write an unit test for it using Reflection? If it is completely unlikely, then writing an unit test based on Reflection is a waste of time. If it is likely, so you should write your test using Reflection too.
Moreover, using the second approach you are able to change the tech stack(For replace .Net with php) used for producing the WebApi, without changing you tests(This is what we expect from a WebApi too).
Finally, you should make a decision! how are you going to use this WebApi? How likely is it to call your WebApi using direct class instantiating?
Note:
It might be irrelevant to your question, but you should concentrate on your Asserts, too. For example asserting ResponseStatusCode and ResponseStatusMsg might not be needed and you can assert only one.
Or what will happen if obj is null? or obj has more than one member?
I'd say that they are not mutually exclusive. The first option is a classical unit test while the second is an integration test as involves more than a single unit of code.
If I had time to write either unit tests or integration tests, I'd pick unit tests as provides a more focused approach and gives, at least in my opinion, the best result from cost benefit.
In some particular projects where I had enough resources to write different suites of tests, I wrote both tests covering approaches. Where the second one would run without mocking anything (or maybe just the persistent storage) so I could test how all the components integrate together.
In relation to good practices, if you want to do real unit test, then you have no option but picking option one as no external dependencies are allowed (HttpClient is an external dependency).
Then, if the time and resources allow it, you could do integration testing for the most critical and/or complex paths.
If you are looking for some non programming You can use Postman, and can create collection of requests and can test multiple requests one by one.
You can use Swagger (aka OpenAPI).
Install Swashbuckle.AspNetCore from nuget.
using Microsoft.OpenApi.Models;
//in Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
}
//in Startup.Configure
public void Configure(IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
Finally, add "launchUrl": "swagger", in launchSettings.json
I used Dapper.Contrib in my Asp.Net Core Web API project.
I encountered a problem while writing a test with xUnit in this project.
For example, here is my method that adds records to my data layer.
public async Task<bool> AddAsync(User entity)
{
await using var connection = _dbConnection.CreateDbConnection();
await connection.OpenAsync();
return await connection.InsertAsync(entity) > 0;
}
My xUnit method that I try to write according to this method is below.
[Fact]
public void AddAsync_Should_Return_As_Expected()
{
var connection = new Mock<DbConnection>();
//Arrange
_userDbConnection.Setup(u => u.CreateDbConnection()).Returns(connection.Object);
//Act
var result = _sut.AddAsync(_user).GetAwaiter().GetResult();
//Assert
//Assert.Equal(result,actual);
}
When I run this test method, I get object not set error in
'return await connection.InsertAsync(entity) > 0;' line.
What exactly is my fault?
I believe what is happening is you are using a mocked connection and trying to call a Dapper method, InsertAsync, on it. The Dapper method is inevitably failing because it is not a real connection.
I'm not sure how much value you get using mocks here. What you really want to know, when testing AddAsync, is does it actually do what you want it to do which is insert data into the database. So if I were you I would turn this test into an integration test by using a real connection instead of a mocked one. One way of doing this is to
Use a test database for the purposes of testing
Before running the test delete all data from the test database
In your assert use Dapper or otherwise to check that a query for the entity brings back the data you expect to be in the database.
I don't necessarily recommend this but another approach could be to use an in memory database. See for example unit testing Dapper Repositories.
I have MVC web app that uses EntityFramework context and it stores it in HttpContext.Current.Items. When HttpContext.Current isn't available then it uses CallContext.SetData to store data in current thread storage. HttpContext is used for web app itself and CallContext is used in unit tests to store the same EF DbContext there.
We are also trying to use async\await as we have library that relays a lot on them, and it works great in web app. But it fails in unit tests as CallContext.SetData isn't restored after thread returns to await block.
Here is simplified sample of the issue:
public async Task Test()
{
ContextUtils.DbContext = new SomeDbContext();
using (ContextUtils.DbContext){
await DoSomeActions();
}
}
public async Task DoSomeActions(){
var data = await new HttpClient().GetAsync(somePage);
// on next line code would fail as ContextUtils.DbContext is null
// as it wasn't synced to new thread that took it
var dbData = ContextUtils.DbContext.SomeTable.First(...);
}
So in that example ContextUtils.DbContext basically sets HttpContext\CallContext.SetData. And it works fine for web app, and fails in unit test as SetData isn't shared and on ContextUtils.DbContext.SomeTable.First(...); line DbContext is null.
I know that we can use CallContext.LogicalSetData\LogicalGetData and it would be shared withing ExecutionContext, but it requires item to be Serializable and i don't want to mark DbContext with serialization attribute as would try to serialize it.
I also saw Stephen's AsyncEx library (https://github.com/StephenCleary/AsyncEx) that has own SynchronizationContext, but it would require me to update my code and use AsyncContext.Run instead of Task.Run, and i'm trying to avoid code updating just for unit tests.
Is there any way to fix it without changing the code itself just to make it work for unit tests? And where EF DbContext should be stored in unit tests without passing it as parameter and to be able to use async\await?
Thanks
OK, there's a lot of things here.
Personally, I would look askance at the use of CallContext.GetData as a fallback to HttpContext.Current, especially since your code makes use of async. Consider using AsyncLocal<T> instead. However, it's possible that AsyncLocal<T> may also require serialization.
I also saw Stephen's AsyncEx library (https://github.com/StephenCleary/AsyncEx) that has own SynchronizationContext, but it would require me to update my code and use AsyncContext.Run instead of Task.Run, and i'm trying to avoid code updating just for unit tests.
A couple of things here:
You shouldn't be using Task.Run on ASP.NET in the first place.
Using Task.Run will prevent the (non-logical) call context from working, as well as HttpContext.Current. So I assume that your code is not accessing the DbContext from within the Task.Run code.
It sounds like your best option is to use my AsyncContext. This class was originally written for asynchronous unit tests (back before unit test frameworks supported asynchronous unit tests). You shouldn't need to update your code at all; just use it in your unit tests:
public void Test()
{
AsyncContext.Run(async () =>
{
ContextUtils.DbContext = new SomeDbContext();
using (ContextUtils.DbContext)
{
await DoSomeActions();
}
});
}
Avoid using async void. Make the test method await-able by used Task
[TestMethod]
public async Task Test() {
ContextUtils.DbContext = new SomeDbContext();
using (ContextUtils.DbContext) {
await DoSomeActions();
}
}
HttpContext is not available during unit test as it is tied to IIS which is not present during unit tests. Avoid tightly coupling your code to HttpContext treat it like a 3rd party resource and abstract it away behind code you can control. It will make testing maintaining and testing your code easier. Consider reviewing your current design.
I'm just getting started with RavenDB and I like it so far. I am however stuck on how I should unit test controller actions that interact with it.
All the questions/articles I have found like this one: Unit testing RavenDb queries tell me I should use RavenDB in memory rather than mock it away but I cannot find a solid example of how this is done.
For example I have a controller action to add an employee to the database (yes, it's overly simplified but I don't want to complicate the issue)
public class EmployeesController : Controller
{
IDocumentStore _documentStore;
private IDocumentSession _session;
public EmployeesController(IDocumentStore documentStore)
{
this._documentStore = documentStore;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
_session = _documentStore.OpenSession("StaffDirectory");
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (_session != null && filterContext.Exception == null) {
_session.SaveChanges();
_session.Dispose();
}
}
[HttpGet]
public ViewResult Create()
{
return View();
}
[HttpPost]
public RedirectToRouteResult Create(Employee emp)
{
ValidateModel(emp);
_session.Store(emp);
return RedirectToAction("Index");
}
How can I verify what was added to the database in a unit test? Does anyone have any examples of unit tests involving RavenDb in MVC applications?
I'm using MSTest if that matters but I'm happy to try and translate tests from other frameworks.
Thanks.
EDIT
Ok, my test initialise creates the document store that is injected into the controller constructor, but when I run my test the OnActionExecuting event doesn't run so there is no session to use and the test fails with a null reference exception.
[TestClass]
public class EmployeesControllerTests
{
IDocumentStore _store;
[TestInitialize]
public void InitialiseTest()
{
_store = new EmbeddableDocumentStore
{
RunInMemory = true
};
_store.Initialize();
}
[TestMethod]
public void CreateInsertsANewEmployeeIntoTheDocumentStore()
{
Employee newEmp = new Employee() { FirstName = "Test", Surname = "User" };
var target = new EmployeesController(_store);
ControllerUtilities.SetUpControllerContext(target, "testUser", "Test User", null);
RedirectToRouteResult actual = target.Create(newEmp);
Assert.AreEqual("Index", actual.RouteName);
// verify employee was successfully added to the database.
}
}
What am I missing? How do I get the session created to use in the test?
After you've run your unit test, just assert that there is a new doc in the database and that it has the right fields set.
var newDoc = session.Load<T>(docId)
or
var docs = session.Query<T>.Where(....).ToList();
RavenDB in-memory mode is there so that you don't have to mock it out, you just do the following:
Open a new in-memory embedded doc store (with no data)
If needed insert any data your unit test needs to run
RUN the unit test
Look at the data in the in-memory store and see if it has been updated correctly
Update If you want a full sample, take a look at how the RacoonBlog code does it, this is the code running Ayende's blog. See these 2 files:
BlogConfigBehavior.cs
RaccoonControllerTests.cs
How can I verify what was added to the database in a unit test?
You don't. We don't test such things in unit tests. This is a responsibility for integration tests, NOT unit testing.
If you want to unit test classes, which depend on some external source (like your db), mock the database access.
EDIT:
To correct some mentioned mistakes, I'll quote definition from MSDN (however all other resources agree with that):
The primary goal of unit testing is to take the smallest piece of
testable software in the application, isolate it from the remainder of
the code, and determine whether it behaves exactly as you expect.
Without mocking you are ignoring the basic principles of Unit testing - isolation and testing the smallest piece possible. Unit test need to be persistent-ignorant and shouldn't be relying on some external class. What if the db changes over time? Rewrite all tests, even though the functionality stays exactly the same?
COME ON. You can give me -1 how many times you want, but that won't make you right.
As that thread you linked to mentioned use the EmbeddableDocumentStore by embedding RavenDB.
Here's how to set that up:
http://msdn.microsoft.com/en-us/magazine/hh547101.aspx
Here's how to use the repository pattern with raven, so you can test easily:
http://novuscraft.com/blog/ravendb-and-the-repository-pattern
First of all, I am aware that this question is dangerously close to:
How to MapPath in a unit test in C#
I'm hoping however, that it has a different solution. My issue follows:
In my code I have an object that needs to be validated. I am creating unit tests for each validation method to make sure it is validating correctly. I am creating mock data and loading it into the object, then validating it. The problem is that within the validation, when an error occurs, an error code is assigned. This error code is used to gather information about the error from an xml file using Server.MapPath. However, when trying to get the xml file, an exception is thrown meaning the file cannot be found.
Since MapPath is in my validation code, and not my unit test, how do I get my unit test to recognize the path? Does this question make sense?
Error Line (In my Validation code NOT my unit test):
XDocument xdoc = XDocument.Load(HttpContext.Current.Server.MapPath("App_Data/ErrorCodes.xml"));
Simplified: The Unit Test calls a method in my program that calls Server.MapPath which then fails.
I would abstract out the "filename provider" into an class that simply returns a location, then you can mock it much, much easier.
public class PathProvider
{
public virtual string GetPath()
{
return HttpContext.Current.Server.MapPath("App_Data/ErrorCodes.xml");
}
}
Then, you can either use the PathProvider class directly...
PathProvider pathProvider = new PathProvider();
XDocument xdoc = XDocument.Load(pathProvider.GetPath());
Or mock it out in your tests:
PathProvider pathProvider = new MockPathProvider(); // using a mocking framework
XDocument xdoc = XDocument.Load(pathProvider.GetPath());
After some rigorous googling and some help from a colleague we came up with a simple solution already built into .net
Above the unit tests that accesses the validation process, I added:
[TestMethod()]
[HostType("ASP.NET")]
[UrlToTest("http://localhost:###/upload_file.aspx")]
[AspNetDevelopmentServerHost("Path To Web Application", "Path To Web Root")]
This works perfectly. Basically, when the test is called, it loads the URL with the specified unit test in the page load. Since it is a web site that is now calling the unit test, the validation will have access to Server.MapPath. This solution may not work for everyone, but it was perfect for this. Thanks to all you contributed.
Try using Rhino Mocks or an alternative mocking framework to Mock the httpContext (or other dependent objects)
Or you could write your own mock objects.
Or write a MapPathWrapper class, inherit from a MapPathWrapperBase class for your real environment, then in for your unit tests create a MockMapPathWrapper object.
There should be plenty of examples for mocking on SO.
Here's one I asked:
How to use Rhino Mocks to Mock an HttpContext.Application
UPDATE
I only have experience doing this with the Asp.Net MVC, with webforms I imagein it would be a lot more difficult because of the lack of an HttpContextBase class.
I would extract methods that accept your dependencies as arguments:
public void Validate(HttpContext context)
{
ValidatePath(context.Server.MapPath("App_Data/ErrorCodes.xml"));
}
public void ValidatePath(string path)
{
XDocument xdoc = XDocument.Load(path);
ValidateDocument(xdoc);
}
public void ValidateDocument(XDocument xdoc)
{
// Original code
}
You can then test the various methods independently. For example, testing how ValidatePath() handles a missing file.