我想对使用Netty构建的套接字服务器进行一些单元测试。

套接字服务器具有以下简单代码:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class SocketServer implements Runnable {

    private int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    private ChannelFuture channelFuture;
    private ServerBootstrap bootstrap;

    public SocketServer(int port) {
        this.port = port;
        this.bossGroup = new NioEventLoopGroup();
        this.workerGroup = new NioEventLoopGroup();
    }

    public int getPort() {
        return port;
    }

    @Override
    public void run() {
        try {
            bootstrap = new ServerBootstrap();
            bootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline()
                                    .addLast(new ReceiveMessageServerHandler())
                                    .addLast(new ParseMessageServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

            // Bind and start to accept incoming connections.
            channelFuture = bootstrap.bind(port).sync();

            // Wait until the server socket is closed
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();

        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public void shutdown() throws InterruptedException {
        channelFuture.channel().close();
    }

}

我首先在MessageHandlers上接收以'\n'分隔的文本消息。我非常需要一个telnet客户端。

我想测试是否可以将不同的消息发送到服务器,并在一定时间内收到某些预期的响应。

我尝试使用Citrus Framework,但无法获得任何结果,因为它没有提供适当的纯文本协议(protocol)(我尝试了Rest,Soap等,但它们对我没有好处)。我在Citrus Reference 2.4中找不到答案。

Citrus 2.4 Reference - HTML Version

最佳答案

您也可以为此使用Citrus Apache Camel集成。您需要citrus-camel模块和camel-netty(http://camel.apache.org/netty.html)或camel-netty4(http://camel.apache.org/netty4.html)依赖项。然后,您可以直接使用Camel Netty组件发送消息:

@Test
@CitrusTest
public void sendNettyMessageTest() {
    status(Status.DRAFT);
    //sends data to server
    send("camel:netty4:tcp://localhost:9123").payload("Message 1");
    send("camel:netty4:tcp://localhost:9123").payload("Message 2");
}

这利用了Citrus中的动态端点,在测试运行时创建了端点配置。因此,这里几乎不需要任何其他配置!

09-04 13:44