Small temp file helper for integration tests
I’m writing some integration tests and needed to be able to create/cleanup temp files during the test. So I’ve created a small helper for that (so that the file will be deleted even if the test fails).
[TestClass]
public class WebClientTests
{
[TestMethod]
public void Upload()
{
var subject = new EfecteWebClient(new HardCodedConfig());
var repos = new ChangeRequestRepository(subject);
var changeRequest = repos.Get("ACHG-00002978");
UploadResult result;
using (var tempFile = new TempFile("Hello world"))
{
var stream = new FileStream(tempFile.FullPath, FileMode.Open);
result = subject.Upload(() => changeRequest.Title, UploadType.Set, new HttpFile("myFile", "mydocument.txt", stream));
}
Assert.IsFalse(result.Errors.Any());
}
}
See? The TempFile class implements IDisposable so that the tests won’t be cluttered with the cleanup.
Implementation:
public class TempFile : IDisposable
{
public TempFile()
{
}
public TempFile(string contents)
{
if (contents == null) throw new ArgumentNullException("contents");
FullPath = Path.GetTempFileName();
File.WriteAllText(FullPath, contents);
}
public string FullPath { get; private set; }
public void Dispose()
{
File.Delete(FullPath);
}
public string Read()
{
return File.ReadAllText(FullPath);
}
public void Write(string text)
{
if (text == null) throw new ArgumentNullException("text");
File.WriteAllText(FullPath, text);
}
}