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

人盡茶涼 提交于 2019-12-12 03:48:36

问题


I'm trying to test a method from a Test project like so:

[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);
}

...but it blows up; I get, "Could not find a part of the path."

It works fine, though, when I call it like this from the project's main form's Load event:

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");

...I see the "emailing succeeded" message.

The method under test conditionally creates a folder:

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

So virtually the same code works in the real project, but fails from the Test project; I assume the crux of the problem is the creation of the folder. Are tests, or "remote" code disallowed from manipulating the file system in this way, is that what's happening here? If so, how can a method that does such things be tested?

UPDATE

Note: I am able to read from the file system; this test succeeds:

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

UPDATE 2

And I'm able to manipulate files, too:

[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));
}

...so...?!?

UPDATE 3

I temporarily commmented out the folder creation code, and it still breaks, so it wasn't that...maybe Testing and Outlook Interop don't mix?

UPDATE 4

For Arturo:

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;
}

UPDATE 5

More for Arturo:

// 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); 
}

回答1:


I think you should do better checks about reports folder.

Try replacing:

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

with:

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

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

Also, you should use Path class to work with paths:

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


来源:https://stackoverflow.com/questions/35660887/if-creating-files-from-code-that-is-exercised-via-tests-is-disallowed-how-can-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!