I'm trying to figure out how to write unit tests for a server application that requieres sockets in C#. I need to read from a socket in order to proccess the request. In Java I could avoid sockets by using Streams, so when writing unit tests i could easily convert a string into a stream.
// ====== Input ======
InputStream socketInputStream = new InputStream(socket.getInputStream());
// or using string instead like this
InputStream socketInputStream = new ByteArrayInputStream("string".getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(socketInputStream));
// ====== Output ======
OutputStream socketOutputStream = new OutputStream(socket.getOutputStream());
// I need to write byte[] to the stream
BufferedOutputStream out = new BufferedOutputStream(socketOutputStream);
I only found NetworkStream() but it also requires a socket.
How can I achieve this in C# so i can create Streams without sockets? And how can I write to a Stream and read it again to see if the message is correct?
[nkvu - Moving this out of the comments and into the answer based on the poster's question against my comment; not trying to steal @Andrey's thunder]
So in Java you are doing:
InputStream socketInputStream = new ByteArrayInputStream("string".getBytes());
In your unit tests (I am assuming, based on your original question).
In C# you could do:
Stream socketInputStream = new MemoryStream(Encoding.UTF8.GetBytes("string"));
That would be (noting I haven't done real-world Java for a while) a C#-ish equivalent. Because MemoryStream is just a subclass of Stream you can use the general Stream methods to read data from it (e.g. Read()).
You could also write to a MemoryStream, e.g:
bytes[] toWrite = Encoding.UTF8.GetBytes("Write to stream");
Stream writeToStream = new MemoryStream();
writeToStream.Write(toWrite, 0, toWrite.Length);
HTH, Nathan
You can use MemoryStream in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With