【发布时间】:2016-05-09 12:05:13
【问题描述】:
我对 C# 很陌生,并且创建了一个包含两个测试的单元测试项目。但是,我在其中一项测试中得到了一个奇怪的结果。
当我单击“运行所有测试”时,测试失败。但是当我立即点击“运行失败的测试”时,测试通过了。
请问是什么问题?
这里是测试方法
[TestMethod]
public void GetFiles_WithNoIgnoreValueProvided_ReturnsAllFiles()
{
var path = @"C:\Users\myDocs\Desktop\New folder";
var thefiles = Filer.GetFiles(path) as List<string>;
Assert.AreEqual(3, thefiles.Count);
}
编辑 测试失败的消息是“Test Failed - Assert.Areequal failed. Expected: 3 Actual 2.
编辑二: 这是我的 Filer 类。我正在尝试创建一个静态类,可用于返回目录中的所有文件(以及递归的任何子目录)
public static class Filer
{
private static List<string> ignorethesefiles;
private static List<string> thefiles;
public static IEnumerable<string> GetFiles(string path, IEnumerable<string> ignorefilescontaining = null)
{
if (ignorefilescontaining !=null)
{
ignorethesefiles = new List<string>(); ignorethesefiles.AddRange(ignorefilescontaining);
}
else
{
ignorethesefiles = new List<string>() { "@" };
}
if (File.Exists(path))
{
// This path is a file
ProcessFile(path, ref thefiles);
}
if (Directory.Exists(path))
{
// This path is a directory
//if (ignorethesefiles.Count > 0)
//{
ProcessDirectory(path, ref thefiles, ref ignorethesefiles);
}
return thefiles;
}
private static void ProcessDirectory(string path, ref List<string> thefiles, ref List<string> ignorethesefiles)
{
//Process files in the directory
IEnumerable<string> filesindir = Directory.GetFiles(path);
foreach (var filename in filesindir)
{
// if (ignorefilescontaining != string.Empty)
// if (ignorethesefiles.Count > 0)
// {
if (!ignorethesefiles.Any(s=>filename.Contains(s)))
{
ProcessFile(filename, ref thefiles);
}
// ProcessFile(filename, ref thefiles);
// }
}
//Recurse subdirectories
IEnumerable<string> subdirectories = Directory.GetDirectories(path);
foreach (var sub in subdirectories)
{
ProcessDirectory(sub, ref thefiles, ref ignorethesefiles);
}
}
private static void ProcessFile(string path, ref List<string> thefiles)
{
if (thefiles == null)
{
thefiles = new List<string>();
thefiles.Add(path);
}
else
{
thefiles.Add(path);
}
}
}
更新:
感谢@Matthewwatson 的以下改进(我认为 :))它肯定不那么冗长:
public static class SOFinder
{
public static IEnumerable<string>GetListOfFiles(string path,string pattern, SearchOption searchoption)
{
var files = Directory.GetFiles(path, pattern, SearchOption.AllDirectories);
return files;
}
}
现在阅读 LINQ 以了解如何过滤结果以生成不包含给定字符串的列表。或者有人可以给我一个提示吗?
还将寻求模拟文件系统,然后再次测试并更新结果。干杯
干杯
【问题讨论】:
-
输出有什么错误,或者失败的实际文件数是多少?
-
单元测试失败的原因是什么?有例外吗?看起来这可能是资源未释放的竞争条件。
-
嗨,谢谢大家的回复。我添加了失败消息。欢呼
-
也许
Filer.GetFiles()中存在一个错误,它没有关闭/处理/清理某些东西,所以当下一次测试运行时某些东西仍然打开,因此它失败了。 -
另外,你可能想重新考虑这样的单元测试,你基本上是在测试框架代码(即不是你的),这是不可取的。
标签: c# visual-studio unit-testing