如何断言所需的文件已下载Selenium c# chromedriver



我正在编写一个基于Selenium c#的自动化测试,使用chromedriver。我正在测试点击按钮后是否下载了某个文件。每次下载时,文件名都会改变,但始终是。pdf格式下载路径预设为"c:UserstestcaseDownloads"我根本找不到一个工作的c#代码来验证/断言文件已被下载。任何形式的帮助都会非常感激。下面的代码

class FileIsDownloaded : OpenCloseDriver
{
[TestCase]
public void UserIsAbleToDownloadTheFile()
{
driver.Url = "https://MYWEBPAGE.COM";
IWebElement InitiateDownload = driver.findelement(By.Xpath(my-xpath);
InitiateDownload.Click();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
????????????

试试这个,应该可以工作。但是这里有另一个问题,你需要在每次断言之后删除这个文件,因为测试用例总是通过的,如果你下载任何。pdf文件,即使只有一次。让我知道它是否适用于你,然后我们可以尝试删除文件。

string pdfFile = @"c:UserstestcaseDownloads", "*.pdf)";
Console.WriteLine(File.Exists(pdfFile) ? "File exists." : "File does not exist.");

所以我设法弄清楚如何验证文件已被下载&验证后,文件被删除。超时后跟着代码。c#中的代码


int PDFdownloaded = Directory.GetFiles(@"C:UserstestcaseDownloads", "*.pdf", SearchOption.AllDirectories).Length;
if (PDFdownloaded > 0)
{
Assert.IsTrue(PDFdownloaded > 0);
}
else
{
Assert.IsTrue(PDFdownloaded < 0);
}
string[] PDF = Directory.GetFiles(@"C:UserstestcaseDownloads", "*.pdf");
foreach (string file in PDF)
{
File.Delete(file);

最新更新