[英]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. 我有服务类的单元测试,我想模拟AppDomain.CurrentDomain.BaseDirectory
for var someCLass = new SomeClass()
而不更改此类。
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. 但是如果测试运行, AppDomain.CurrentDomain.BaseDirectory
将被更改为不同的目录。
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
. 我不想使用typemock Isolate,但它看起来像一个可能的修复,我想找到不同的方法来解决这个可能与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. DateTime.Now是另一个可以这种方式注入的例子。
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 这种方法的另一个好处是你不需要担心嘲笑任何东西,你的测试代码变得非常简单和实际可维护
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.