NUnit: Test for file system

L

Luigi

Hi all,
with NUnit (C#) which is the better way to implement some tests to operate
on a file in the file system?
For instance: file exists, file read and file write.

Thanks in advance.
 
N

Nicholas Paldino [.NET/C# MVP]

Luigi,

Why not just use the classes in the System.IO namespace to determine if
the file exists, and to read/write from/to the file?
 
P

Peter Morris

Use dependency injection or the service pattern to obtain a reference to an
interface that provides these functions, and use mocks to mock them during
testing.



Pete
 
S

sloan

I'm confused about what you're asking.


bool b = System.IO.File.Exists(@"C:\myfile.txt");
Assert.AreEqual(true,b);


That looks like the basic setup to me.
 
L

Luigi

Yes, something similar.
Not also verify that the file exists, but also that I can read it.
A full tests for file system access and reading.

Luigi
 
R

raulavi

i od have something like this

public static bool IsFileWritable(string fileName)
{
//write at least one single line into file,
//used by unit test
try
{
//to clear file use
// FileInfo afileinfo = new FileInfo("list.txt");
afileinfo.Delete();
string line = String.Empty;
StreamWriter oSWriter = new StreamWriter(fileName);
oSWriter.WriteLine("TEST:" +
DateTime.Today.ToString("yyMMdd"));
oSWriter.Close();

//Chk segments in created file
StreamReader aSR = new StreamReader(fileName);

line = aSR.ReadLine();
if (line == null) return false;
if (!line.StartsWith("TEST:")) return false;

aSR.Close();
oSWriter.Dispose(); //remove from memory,does not delete file
return true;
}
catch (Exception)
{
return false;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top