[英]how to unit test netty handler that inclued i/o file in it?
in channelRead of the channelhandleradapter i am writing to a file , i know how to use embeddedchannel to unit test netty handlers , but how to unit test this handler when we are doing file I/O inside it(ChannelRead) ? 在我正在写入文件的channelhandleradapter的channelRead中,我知道如何使用Embeddedchannel对Netty处理程序进行单元测试,但是当我们在其中处理文件I / O(ChannelRead)时如何对该处理程序进行单元测试? something like mock with no i/O file dependency .
类似于模拟,没有I / O文件依赖性。
public class LogHandler : ChannelHandlerAdapter
{
const string Path = @"L:\Log.txt";
public override void ChannelActive(IChannelHandlerContext context)
{
base.ChannelActive(context);
}
public override Task WriteAsync(IChannelHandlerContext context, object message)
{
Logger.SentLog(message as IByteBuffer);
return context.WriteAsync(message as IByteBuffer);
}
public override void ChannelRead(IChannelHandlerContext context, object message)
{
string msg = Convertor.ByteBufferToString(message as IByteBuffer);
IByteBuffer initialMessage = Unpooled.Buffer(1024);
byte[] messageBytes = Encoding.UTF8.GetBytes(msg);
initialMessage.WriteBytes(messageBytes);
using (StreamWriter writer = new StreamWriter(Path, true))
{
writer.WriteLine($"(Read){System.DateTime.Now} -> {BitConverter.ToString(messageBytes).Replace("-"," ")}");
}
if (msg != "Timeout")
{
base.ChannelRead(context, message);
}
}
}
You class depends on the StreamWriter
class. 您的类取决于
StreamWriter
类。 You need to change your class in such way that you provide these dependency from the caller and that you can mock it in your unit tests. 您需要以这样的方式更改您的类,以便您从调用方提供这些依赖关系,并可以在单元测试中对其进行模拟。 Therefore, you could create a simple wrapper class for the
StreamWriter
instantiation, use this wrapper class in your class and inject it in the constructor/ per setter. 因此,您可以为
StreamWriter
实例创建一个简单的包装器类,在您的类中使用该包装器类,然后将其注入构造器/每个设置器中。 And in your unit test setup up the mock to return a local StreamWriter
that you can use to verify the content written. 并且在您的单元测试中,设置模拟以返回本地
StreamWriter
,您可以使用该StreamWriter
来验证编写的内容。
You can still use EmbeddedChannel
. 您仍然可以使用
EmbeddedChannel
。 Just use writeInbound(...)
and verify it returns false
. 只需使用
writeInbound(...)
并验证它返回false
。 Then once you called channel.finish()
verify what was written in the file. 然后,一旦调用
channel.finish()
验证文件中写入的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.