简体   繁体   中英

How to mock AppDomain.CurrentDomain.BaseDirectory

I have unit test with service class, i want to mock AppDomain.CurrentDomain.BaseDirectory for var someCLass = new SomeClass() without changes this class.

In this class it is used as a path to generate new paths for reading files. But if test running, AppDomain.CurrentDomain.BaseDirectory will be changed to different directory.

I don't want use typemock Isolate, but it looks like a possible fix, i want found different way to resolve this maybe with Moq .

public SomeClass
{
 SomeClass()
 {
  //Use something like that
  var path = AppDomain.CurrentDomain.BaseDirectory;
 }
}

//Test Class
[TestFixture]
public class TestClass
{
 private SomeClass someClass;

 [Test]
 public void SomeTest()
 {
  someClass = new SomeClass();
 }
}

//Change AppDomain.CurrentDomain.BaseDirectory for unit test without changing original class.

You may not want to change your class but that is precisely what you should be doing. If you want to do some proper testing, you need to make sure that the code is actually testable to begin with.

There is a simple solution which doesn't involve a lot of changes, simply add a new parameter, either to the constructor, or to the method you actually want to test and pass the actual path to it.

Your code could look like this:

public SomeClass 
{
   public SomeClass(string baseLocation)
}

then when you instantiate it you can simply do something like

var basePath = AppDomain.CurrentDomain.BaseDirectory;

var someClass = new SomeClass(basePath);

This now allows you to inject the path from wherever, tests included. If you want testable code then you need to remove such dependencies. DateTime.Now is another example that can be injected this way.

Another benefit of this method is that you don't need to worry about mocking anything and your testing code becomes very simple and actually maintainable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM