Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#使用套接字的单元测试_C#_Unit Testing_Sockets - Fatal编程技术网

c#使用套接字的单元测试

c#使用套接字的单元测试,c#,unit-testing,sockets,C#,Unit Testing,Sockets,我试图找出如何为需要C#中的套接字的服务器应用程序编写单元测试。我需要从套接字读取数据才能处理请求。在Java中,我可以通过使用流避免套接字,因此在编写单元测试时,我可以轻松地将字符串转换为流 // ====== Input ====== InputStream socketInputStream = new InputStream(socket.getInputStream()); // or using string instead like this InputStream socket

我试图找出如何为需要C#中的套接字的服务器应用程序编写单元测试。我需要从套接字读取数据才能处理请求。在Java中,我可以通过使用流避免套接字,因此在编写单元测试时,我可以轻松地将字符串转换为流

// ====== 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);
我只找到NetworkStream(),但它还需要一个套接字

如何在C#中实现这一点,以便创建没有套接字的流?
我怎样才能写一条流,然后再读一遍,看看消息是否正确?

你可以用C.

[nkvu-将此从评论中移出,并根据海报上针对我评论的问题进行回答;而不是试图窃取@Andrey的雷声]

因此,在Java中,您正在做:

InputStream socketInputStream = new ByteArrayInputStream("string".getBytes());
在您的单元测试中(我假设,基于您最初的问题)

在C#中,您可以执行以下操作:

Stream socketInputStream = new MemoryStream(Encoding.UTF8.GetBytes("string")); 
这将是(注意,我已经有一段时间没有使用真实世界的Java了)C#ish的等价物。因为MemoryStream只是的一个子类,所以可以使用常规流方法从中读取数据(例如read()

您也可以写入MemoryStream,例如:

bytes[] toWrite = Encoding.UTF8.GetBytes("Write to stream");
Stream writeToStream = new MemoryStream();
writeToStream.Write(toWrite, 0, toWrite.Length);

嗯,Nathan

可能是,后面有一个字节[]。如果你想写一个字符串,并且你可以“硬编码”一个编码,你可以使用类似的东西将字符串转换成字节[],如果它有字节[]支持,我如何使用它,从套接字读取?程序必须能够获取流,无论它是由字符串还是套接字创建的