Daily Archives: April 2, 2007

Simulating a Server in .Net (C#)

I recently had a need to simulate an FTP server connection in some unit tests. Rather than developing a full test-server, for this purpose, I could easily simulate an FTP stream by creating it in memory, and then passing that stream to the functions  that expect it:

public Stream CreateTestStream(string text) { byte[] buff = Encoding.ASCII.GetBytes(text); return new MemoryStream(buff, false); }

This function merely accepts text (FTP is text-based after all), and returns a memory stream. I can then use it in a unit test:

[Test] [ExpectedException(typeof(FtpException),"InvalidResponse")] public void FtpResponse_Constructor_BadStream_InvalidCode() { using (Stream s = CreateTestStream("NoErrorCode")) { FtpResponse response = new FtpResponse(s); } }