I am currently unit testing a piece of code that should throw an exception when a file cannot be deleted.
Here’s the piece of code I am trying to test:
public void DeleteFile(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception e)
{
throw FileServiceException.BecauseCouldNotDeleteFile(e);
}
}
The test case I originally created worked perfectly fine on Windows. But our CI/CD runs on Linux images.
Here’s the test case:
[Fact]
public void DeleteFile_Throws_ExceptionIfFileCannotBeDeleted()
{
var filePath = $"{Path.GetTempPath()}{Guid.NewGuid()}.jpeg";
using var file = File.Create(filePath);
Assert.Throws<FileServiceException>(() =>_service.DeleteFile(filePath));
// Make sure to delete file after the test
_service.DeleteFile(filePath);
}
This is my current testcase. I’ve tried setting the UnixFileMode
to None, and I’ve tried setting the FileAttributes
to Hidden
using: File.SetAttributes(filePath, FileAttributes.Hidden);
but none of those seem to work.
[Fact]
public void DeleteFile_Throws_ExceptionIfFileCannotBeDeleted()
{
var filePath = $"{Path.GetTempPath()}{Guid.NewGuid()}.jpeg";
File.Create(filePath);
File.SetUnixFileMode(filePath, UnixFileMode.None);
Assert.Throws<IOException>(() =>_service.DeleteFile(filePath));
// Make sure to delete file after the test
_service.DeleteFile(filePath);
}
kwerie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.