如果不允许从通过测试执行的代码创建文件,那么如何测试这些方法?

If creating files from code that is exercised via Tests is disallowed, how can such methods be tested?

我正在尝试测试来自测试项目的方法,如下所示:

[TestMethod]
public void TestEmailGeneratedReport()
{
    List<String> recipients = new List<string>();
    recipients.Add("bclayshannon@hotmail.net");
    recipients.Add("axx3andspace@male.edu");
    recipients.Add("cshannon@PlatypiRUs.com");
    bool succeeded = RoboReporterConstsAndUtils.EmailGeneratedReport(recipients);
    Assert.IsTrue(succeeded);
}

...但是它爆炸了;我得到,“找不到路径的一部分。

不过,当我从项目的主窗体的加载事件中这样调用它时,它工作正常:

List<String> recipients = new List<string>();
recipients.Add("bclayshannon@hotmail.net");
recipients.Add("axx3andspace@male.edu");
recipients.Add("cshannon@PlatypiRUs.com");
bool succeeded = 
    RoboReporterConstsAndUtils.EmailGeneratedReport(recipients);
if (succeeded) MessageBox.Show("emailing succeeded");

...我看到 "emailing succeeded" 消息。

测试方法有条件创建文件夹:

if (string.IsNullOrWhiteSpace(uniqueFolder))
{
    uniqueFolder = GetUniqueFolder("Test");
    ConditionallyCreateDirectory(uniqueFolder);
}

所以几乎相同的代码在真实项目中工作,但在测试项目中失败;我认为问题的症结在于文件夹的创建。是否不允许测试或 "remote" 代码以这种方式操作文件系统,这是这里发生的事情吗?如果是这样,如何测试执行此类操作的方法?

更新

注意:我能够从文件系统读取;此测试成功:

[TestMethod]
public void TestGetLastReportsGenerated()
{
    string testFolderThatHasExcelFiles = "C:\Misc";
    FileInfo[] aBunchOfFiles = 
        RoboReporterConstsAndUtils.GetLastReportsGenerated(
            testFolderThatHasExcelFiles);
    Assert.IsTrue(aBunchOfFiles.Length > 0);
}

更新 2

而且我还能操作文件:

[TestMethod]
public void TestMarkFileAsSent()
{
    string fileToRename = "C:\Misc\csharpExcelTest.xlsx";
    string desiredRenamedFileName = "C:\Misc\csharpExcelTest_PROCESSED.xlsx";
    RoboReporterConstsAndUtils.MarkFileAsSent(fileToRename);
    bool oldFileNameExists = System.IO.File.Exists(fileToRename);
    bool newFileNameExists = System.IO.File.Exists(desiredRenamedFileName);
    Assert.IsTrue((newFileNameExists) && (!oldFileNameExists));
}

...所以...?!?

更新 3

我暂时注释掉了创建文件夹的代码,但它仍然出错,所以不是...也许测试和 Outlook Interop 不能混用?

更新 4

对于阿图罗:

internal static bool EmailGeneratedReport(List<string> recipients)
{
    bool success = true;
    try
    {
        Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
        MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
        Recipients _recipients = mailItem.Recipients;
        foreach (string recip in recipients)
        {
            Recipient outlookRecipient = _recipients.Add(recip);
            outlookRecipient.Type = (int)OlMailRecipientType.olTo;
            outlookRecipient.Resolve();
        }
        mailItem.Subject = String.Format("Platypus Reports generated {0}", GetYYYYMMDDHHMM());

        List<String> htmlBody = new List<string>
        {
            "<html><body><img src=\"http://www.platypiRUs.com/wp-content/themes/platypi/images/pru_logo_notag.png\" alt=\"Platypus logo\" ><p>Your Platypus reports are attached. You can also view them online here:</p>"
        };
        htmlBody.Add("</body></html>");
        mailItem.HTMLBody = string.Join(Environment.NewLine, htmlBody.ToArray());

        // Commented this out to see if it was the problem with the test failing (it wasn't)
        if (string.IsNullOrWhiteSpace(uniqueFolder))
        {
            uniqueFolder = GetUniqueFolder("Test");
            ConditionallyCreateDirectory(uniqueFolder);
        }

        FileInfo[] rptsToEmail = GetLastReportsGenerated(uniqueFolder);
        foreach (var file in rptsToEmail)
        {
            String fullFilename = String.Format("{0}\{1}", uniqueFolder, file.Name);
            if (!File.Exists(fullFilename)) continue;
            if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
            {
                mailItem.Attachments.Add(fullFilename);
            }
            MarkFileAsSent(fullFilename);
        }
        mailItem.Importance = OlImportance.olImportanceHigh;
        mailItem.Display(false);
    }
    catch (System.Exception ex)
    {
        String exDetail = String.Format(ExceptionFormatString, ex.Message,
            Environment.NewLine, ex.Source, ex.StackTrace, ex.InnerException);
        MessageBox.Show(exDetail);
        success = false;
    }
    return success;
}

更新 5

阿图罗的更多内容:

// Provided the unit name, returns a folder name like "C:\RoboReporter\Gramps\201602260807
internal static string GetUniqueFolder(string _unit)
{
    if (uniqueFolder.Equals(String.Empty))
    {
        uniqueFolder = String.Format("{0}\{1}\{2}", OUTPUT_DIRECTORY, _unit, GetYYYYMMDDHHMM());
    }
    return uniqueFolder;
}

internal static FileInfo[] GetLastReportsGenerated(string _uniqueFolder)
{
    DirectoryInfo d = new DirectoryInfo(_uniqueFolder);
    return d.GetFiles(ALL_EXCEL_FILE_EXTENSION); 
}

我认为你应该更好地检查报告文件夹。

尝试替换:

if (string.IsNullOrWhiteSpace(uniqueFolder))
{
    uniqueFolder = GetUniqueFolder("Test");
    ConditionallyCreateDirectory(uniqueFolder);
}

与:

if (string.IsNullOrWhiteSpace(uniqueFolder))
    uniqueFolder = GetUniqueFolder("Test");

if (!Directory.Exists(uniqueFolder))
    ConditionallyCreateDirectory(uniqueFolder);

此外,您应该使用 Path class 来处理路径:

String fullFilename = Path.Combine(uniqueFolder, file.Name);