如果不允许通过测试从代码中创建文件,那么如何测试这些方法? [英] If creating files from code that is exercised via Tests is disallowed, how can such methods be tested?

查看:153
本文介绍了如果不允许通过测试从代码中创建文件,那么如何测试这些方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



它可以正常工作,当我从

  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 $($ if $($) $ b {
uniqueFolder = GetUniqueFolder(Test);
ConditionallyCreateDirectory(uniqueFolder);





$ b

因此,实际上相同的代码在真实项目中工作,但是在测试项目;我认为问题的症结在于文件夹的创建。测试或远程代码是否被这种方式操纵文件系统,是这里发生了什么?如果是这样的话,一个方法如何测试呢?



UPDATE



注意: > am 能够从文件系统中读取;这个测试成功:

pre $
$ TestB $ b $ testFolderThatHasExcelFiles =C:\\Misc;
FileInfo [] aBunchOfFiles =
RoboReporterConstsAndUtils.GetLastReportsGenerated(
testFolderThatHasExcelFiles);
Assert.IsTrue(aBunchOfFiles.Length> 0);



$ b $ h2更新2

我也能够操作文件:

pre $ $ $ $ $ $ $ $ public void TestMarkFileAsSent()
{
string fileToRename =C:\ \\
字符串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 ...?!?



更新3



我临时分配了文件夹创建代码,但它仍然中断,所以不是这样...也许测试和展望Interop不混用?



更新4



对于Arturo:

  internal static bool EmailGeneratedReport(List< string> recipients)
{
bool success = true;
尝试
{
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
收件人_recipients = mailItem.Recipients;
foreach(收件人中的字符串收件人)
{
收件人outlookRecipient = _recipients.Add(recip);
outlookRecipient.Type =(int)OlMailRecipientType.olTo;
outlookRecipient.Resolve();

mailItem.Subject = String.Format(Platypus Reports generated {0},GetYYYYMMDDHHMM());

列表< String> htmlBody =新列表< string>
{
< html>< body>< img src = \http://www.platypiRUs.com/wp-content/themes/platypi/images/pru_logo_notag.png\\ alt = \\Platypus logo\>< p>您的鸭嘴兽报告已附上,您也可以在这里在线查看:< / p>
};
htmlBody.Add(< / body>< / html>);
mailItem.HTMLBody = string.Join(Environment.NewLine,htmlBody.ToArray());

//评论这是否是测试失败的问题(不是)
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);
成功= false;
}
返回成功;



$ b $ h $ UPDATE 5

更多的Arturo:

  //提供单位名称,返回一个文件夹名称,例如C:\\RoboReporter\\ \\\Gramps\\\201602260807 
内部静态字符串GetUniqueFolder(字符串_unit)
{
if(uniqueFolder.Equals(String.Empty))
{
uniqueFolder = String.Format({0} \\\ {1} \\ {2},OUTPUT_DIRECTORY,_unit,GetYYYYMMDDHHMM());
}
return uniqueFolder;


内部静态FileInfo [] GetLastReportsGenerated(string _uniqueFolder)
{
DirectoryInfo d = new DirectoryInfo(_uniqueFolder);
return d.GetFiles(ALL_EXCEL_FILE_EXTENSION);
}


解决方案

检查有关报告的文件夹。



尝试替换:

  if .IsNullOrWhiteSpace(uniqueFolder))
{
uniqu eFolder = GetUniqueFolder(Test);
ConditionallyCreateDirectory(uniqueFolder);

$ / code $ / pre



<$如果(字符串.IsNullOrWhiteSpace(uniqueFolder))
uniqueFolder = GetUniqueFolder(测试); p $ p> $!
$ b if(!Directory.Exists(uniqueFolder))
ConditionallyCreateDirectory(uniqueFolder);

另外,您应该使用 Path 类来使用路径:

 字符串fullFilename = Path.Combine(uniqueFolder,file.Name); 


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

解决方案

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

这篇关于如果不允许通过测试从代码中创建文件,那么如何测试这些方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆