Reputation: 4157
I tend to get surprised these days, but this little bugger really owned me guerilla style:
Method under test : CopyAllFiles(sourceDir, targetDir) - Need not explain what it does, I guess.
In my test, I create both directories before calling the test subject. Furthermore I add three files to the directory created at the sourceDir location. Let the code speak:
FileSystemService serviceUnderTest = new FileSystemService();
string sourcePath= Path.Combine(_dateiPfad, "quelle");
string destinationPath= Path.Combine(_dateiPfad, "ziel");
Directory.CreateDirectory(sourcePath);
Directory.CreateDirectory(destinationPath);
File.Create(Path.Combine(sourcePath , "Foo.txt"));
File.Create(Path.Combine(sourcePath , "Bar.csv"));
File.Create(Path.Combine(sourcePath , "Baz.xls"));
serviceUnderTest.CopyAllFiles(sourcePath, destinationPath);
IEnumerable<string> sourceFiles= from fileName in Directory.GetFiles(sourcePath) select fileName;
IEnumerable<string> destinationFiles= from fileName in Directory.GetFiles(destinationPath) select fileName ;
Assert.IsTrue(sourceFiles.SequenceEqual(destinationFiles));
I get an IOException saying "File is being used by another process". Why can't I access Files I have just created?
Big thx in advance!
Upvotes: 0
Views: 154
Reputation: 8271
File.Create() returns a FileStream of the file created. You need to close the stream before you can access the file in your CopyAllFiles() method:
FileStream foo = File.Create(Path.Combine(sourcePath, "Foo.txt"));
foo.Close();
You could also use WriteAllText to write out your test files:
File.WriteAllText(Path.Combine(sourcePath, "Foo.txt"),"FooTest");
Upvotes: 2