问题描述
当我执行测试用例时,它在我的机器中不存在的路径上失败,并且出现以下错误:
When I execute my test case, it fails for path within my machine which doesn't exist and I am getting below error:
我是否需要某种假冒/伪造品才能通过测试用例,或者我们还有其他方法可以做到这一点?
Do I need some kind of fake/mock here to pass the test case or do we have other way to do this?
Class
public class DemoCls
{
public void Execute()
{
string dataFolder = @"C:\\Data1";
foreach (string X in Directory.EnumerateFiles(dataFolder, "test" + "*.xml"))
{
}
}
}
测试用例
[TestClass()]
public class DemoClsTests
{
[TestMethod()]
public void ExecuteTest()
{
var X = new DemoCls();
X.Execute();
}
}
推荐答案
Class应该重构,以消除与难以测试的实现问题的紧密联系。
Class should be refactored to remove tight coupling to implementation concerns that make it difficult to test.
//...Creat an abstraction that provides the desired behavior as a contract
public interface IDirectoryService {
IEnumerable<string> EnumerateFiles(string path, string searchPattern);
}
在测试时可以创建伪造品/模拟物,以避免与测试相关的陷阱隔离的IO代码。
A fake/mock can be created for when testing to avoid pitfalls associated with testing IO code in isolation.
本来可以使用模拟框架对依赖项进行存根,但是在此示例中,使用了简单的
A mocking framework could have been used for stubbing the dependencies, but for this example using a simple
public class FakeDIrectoryService : IDirectoryService {
IEnumerable<string> files;
public FakeDIrectoryService(IEnumerable<string> files) {
this.files = files;
}
public IEnumerable<string> EnumerateFiles(string path, string searchPattern = null) {
return files;
}
}
现在需要重构类以遵循。
Class needs to be refactored now to follow Explicit Dependencies Principle via constructor and method injection.
public class DemoCls {
IDirectoryService directory;
public DemoCls(IDirectoryService directory) {
this.directory = directory;
}
public void Execute(string dataFolder) {
foreach (var x in directory.EnumerateFiles(dataFolder, "test*.xml")) {
//...
}
}
}
测试可以
[TestClass()]
public class DemoClsTests {
[TestMethod()]
public void ExecuteTest() {
//Arrange
var fakePath = "C:/temp";
var fakeFiles = new[] {
@"C:\\temp\\testfakefilename1.txt",
@"C:\\temp\\testfakefilename2.txt",
@"C:\\temp\\testfakefilename3.txt"
};
var service = new FakeDIrectoryService(fakeFiles);
var sut = new DemoCls(service);
//Act
sut.Execute(fakePath);
//Assert
//perform your assertions
}
}
最后对于生产代码,文件服务的真正实现可以包装任何源,无论是磁盘还是远程服务。
Finally for production code the real implementation of the file service can wrap any source, be it disk or remote service.
例如
public class FileService : IDirectoryService {
public IEnumerable<string> EnumerateFiles(string path, string searchPattern) {
return Directory.EnumerateFiles(path, searchPattern);
}
}
这仅仅是可以做的一个例子。有很多改进的空间,但这应该可以开始。
This is just an example of what can be done. There is a lot of room for improvement but this should get things started.
这篇关于单元测试时找不到目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!