dna*_*non 7 c# sockets unit-testing
我正在试图找出如何为服务器应用程序编写单元测试,该服务器应用程序需要C#中的套接字.我需要从套接字读取以获取请求.在Java中,我可以通过使用Streams来避免套接字,因此在编写单元测试时,我可以轻松地将字符串转换为流.
// ====== 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#中实现这一点,所以我可以创建没有套接字的Streams?如何写入流并再次读取它以查看消息是否正确?
小智 4
[nkvu - 根据发帖者针对我的评论提出的问题,将其从评论中移出并放入答案中;不是想抢@Andrey的风头]
所以在 Java 中你正在做:
InputStream socketInputStream = new ByteArrayInputStream("string".getBytes());
在你的单元测试中(我假设,基于你原来的问题)。
在 C# 中你可以这样做:
Stream socketInputStream = new MemoryStream(Encoding.UTF8.GetBytes("string")); 
这将是(注意我有一段时间没有接触过现实世界的 Java)C# 风格的等价物了。因为 MemoryStream 只是Stream的子类,所以您可以使用通用的 Stream 方法从中读取数据(例如 Read())。
您还可以写入 MemoryStream,例如:
bytes[] toWrite = Encoding.UTF8.GetBytes("Write to stream");
Stream writeToStream = new MemoryStream();
writeToStream.Write(toWrite, 0, toWrite.Length);
HTH,内森
| 归档时间: | 
 | 
| 查看次数: | 996 次 | 
| 最近记录: |