Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# unit tests using sockets

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?

like image 625
dnanon Avatar asked Mar 20 '13 21:03

dnanon


2 Answers

[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

like image 87
nkvu Avatar answered Oct 03 '22 09:10

nkvu


You can use MemoryStream in C#.

like image 23
Andrey Avatar answered Oct 03 '22 07:10

Andrey