Package com.javachat.client

Source Code of com.javachat.client.ChatClientTest

package com.javachat.client;

import com.javachat.shared.MessageHolder;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
* @author Dmitry Levykin
*/
public class ChatClientTest {
    private final static int PORT = 3000;
    private ServerSocketChannel serverSocketChannel;
    private SocketChannel clientSocketChannel;

    @Before
    public void init() throws IOException {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new java.net.InetSocketAddress(PORT));
    }

    @After
    public void stop() throws IOException {
        serverSocketChannel.close();
    }

    @Test(timeout = 100)
    public void sendMessageTest() throws IOException, InterruptedException {
        String message = "Hello!";
        ChatClient chatClient = new ChatClient(null, null, PORT, new ByteArrayInputStream(new byte[]{}));
        chatClient.createChannel();
        chatClient.sendMessage(message);
        clientSocketChannel = serverSocketChannel.accept();
        ByteBuffer buffer = ByteBuffer.allocate(100);
        clientSocketChannel.read(buffer);
        buffer.flip();
        Assert.assertEquals(message, new MessageHolder(100, ChatClient.CHARSET_NAME).readFromBuffer(buffer));
    }

    @Test(timeout = 100)
    public void receiveMessageTest() throws IOException, InterruptedException {
        ChatClient chatClient = new ChatClient(null, null, PORT, new ByteArrayInputStream(new byte[]{}));
        chatClient.createChannel();
        clientSocketChannel = serverSocketChannel.accept();
        // Отправка с сервера
        String serverMessage = "Hello!";
        byte[] serverMessageBytes = serverMessage.getBytes(ChatClient.CHARSET_NAME);
        ByteBuffer buffer = ByteBuffer.allocate(serverMessageBytes.length + 4);
        buffer.putInt(serverMessageBytes.length);
        buffer.put(serverMessageBytes);
        buffer.flip();

        clientSocketChannel.write(buffer);

        // Прием на клиенте
        String message;
        while ((message = chatClient.onRead()) == null) {}
        Assert.assertEquals(serverMessage, message);
    }
}
TOP

Related Classes of com.javachat.client.ChatClientTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.