Resharper nunit unit test – Could not find a part of the path

Possibly save 1 hour of your time: There are times when your unit test depends on input file. To access the file when using nunit 3.8.1, you can use TestContext.CurrentContext.TestDirectory.

[Test]
public void LoadFileInUnitTestProject()
{
var doc = new XmlDocument();

doc.Load(TestContext.CurrentContext.TestDirectory + "\\Services\\CountryProfile\\population.query.xml");

Assert.That(doc, Is.Not.Null);

}

Book ReSharper Essentials

Advertisements

Make methods accessible to unit tests

Possibly save 1 hour of your time: If you would like to create unit tests for your library, you can create the unit tests in a different project to separate the tests and the code.

1. Typically, a good convention is use the same project name and append dot Tests. i.e. MyProjectName.Tests

2. Then you will need to add reference to your project.

3. To access the methods in your project from the tests project, you will need to mark them internal access unless it is already marked as public access.

4. In the AssemblyInfo.cs of your project, you need to add the following the make your project visible to your tests project.

   [assembly: InternalsVisibleTo(“YourProjectName.Tests”)]

There are other methods of testing your protected or private methods, but I find this solution the easiest to configure and maintain.

Mock HttpRequest

Possibly save 2 hours of your time:

We often want to unit test our controller layer with the input request URL. Here is an example of unit test that can mock the HttpRequest within the HttpContext constructor that you can set on your controller.

private HttpContextBase MockCurrentContext()
{
var sb = new StringBuilder();
TextWriter w = new StringWriter(sb);
var context = new HttpContext(new HttpRequest(“”, “http://www.example.com “, “”), new HttpResponse(w));
return new HttpContextWrapper(context);
}

[OneTimeSetUp]
public void OneTimeSetUp()
{
controller = new YourController();
controller.ControllerContext = new ControllerContext(MockCurrentContext(), new RouteData(), controller);
}