0
votes

I have a console application project with NUnit tests in the same project.

I have been trying to apply this solution.

At run-time the solution worked OK. But when I ran the tests by Resharper test runner or NUnit GUI runner, GetExecutingAssembly().Location returned a path like this: d:\Temp\f4ctjcmr.ofr\nojeuppd.fmf\R2Nbs\assembly\dl3\9766f38e\b9496fb3_43cccf01\.
Disabling shadow-copying fixed the problem in both test runners, but new problems appeared (VS is not able to build the project until NUnit Gui is closed). Is there a better solution than disabling shadow-copying?

Update: Environment.GetCommandLineArgs()[0] returned C:\Program Files (x86)\NUnit 2.6.3\bin\ in the tests running in NUnit Gui with shadow-copying enabled.

2

2 Answers

1
votes

Alright, this goes into fun territory.

You should be mocking out this dependency.

Example code:

public interface IApplicationRootService {
    Uri GetApplicationRoot();
}

public class ApplicationRootService : IApplicationRootService {
    public Uri GetApplicationRoot() {
        //etc
    }
}

Now, apply liberally to your code where you're calling getexecutingassembly and whatnot. Inject the IApplicationRootService as a constructor dependency.

Ex:

public class DoWork {
    private IApplicationRootService _applicationRootService;
    public DoWork(IApplicationRootService applicationRootService) {
        _applicationRootService = applicationRootService;
    }
    public void DoSomething() {
        var appRoot = _applicationRooService.GetApplicationRoot();
        //do your stuff
    }
}

Now when you're testing, use a mocking service and mock out the return value of application root to the appropriate folder for nunit to go sniffin'.

Ex code, using nunit and moq:

[Test]
public static void test_do_something() {
    var applicationRootService = new Mock<IApplicationRootService>();
    applicationRootService.Setup(service => service.GetApplicationRoot()).Returns(new Uri("MyRoot", UriKind.Relative);
    var myClass = new DoWork(applicationRootService.Object);
    //continue testing!
}
0
votes

The following solution worked for me. Please vote to its author if it helps you.

As explained in the MSDN forums post, How to convert URI path to normal filepath?, I used the following:

// Get normal filepath of this assembly's permanent directory
var path = new Uri(
        System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
    ).LocalPath;