Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing a Java Chat Application

I have developed a basic Chat application in Java. It consists of a server and multiple client. The server continually monitors for incoming messages and broadcasts them to all the clients. The client is made up of a Swing GUI with a text area (for messages sent by the server and other clients), a text field (to send Text messages) and a button (SEND). The client also continually monitors for incoming messages from other clients (via the Server). This is achieved with Threads and Event Listeners and the application works as expected.

But, how do I go about unit testing my chat application? As the methods involve establishing a connection with the server and sending/receiving messages from the server, I am not sure if these methods should be unit tested. As per my understanding, Unit Testing shouldn't be done for tasks like connecting to a database or network.

The few test cases that I could come up with are:
1) The max limit of the text field
2) Client can connect to the Server
3) Server can connect to the Client
4) Client can send message
5) Client can receive message
6) Server can send message
7) Server can receive message
8) Server can accept connections from multiple clients

But, since most of the above methods involve some kind of network communication, I cannot perform unit testing. How should I go about unit testing my chat application?

like image 706
Epitaph Avatar asked Sep 03 '25 06:09

Epitaph


2 Answers

You should test the server and client in isolation.

The way to do this is to use mock objects to mock either the server (for testing the client) or the client (for testing the server).

A mock server would have the same methods as the real server, but you can decide what they return, i.e. simulate a connection error, a timeout, etc. Because it is a mock, you have full control over the functioning and you don't have to worry about actual connection errors.

For Java, look at the Mockito mocking framework.

like image 94
Frederik Avatar answered Sep 04 '25 20:09

Frederik


Unit tests should be focused on exercising public APIs of each class you have built. However, things get a little tricky when dealing with Swing. Consider swingUnit for unit testing Swing components.

like image 33
ring bearer Avatar answered Sep 04 '25 20:09

ring bearer