added some tests
This commit is contained in:
parent
45bc4e1a1c
commit
61562d58dc
3 changed files with 104 additions and 11 deletions
96
server/src/test/java/server/PortCheckerTest.java
Normal file
96
server/src/test/java/server/PortCheckerTest.java
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
package server;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PortCheckerTest {
|
||||
@Test
|
||||
void portAvailable() {
|
||||
PortChecker checker = new PortChecker();
|
||||
|
||||
int port = 0; //will find a random available port
|
||||
boolean available = checker.isPortAvailable(port);
|
||||
|
||||
assertTrue(available);
|
||||
}
|
||||
@Test
|
||||
void portNotAvailable(){
|
||||
try {
|
||||
ServerSocket socket = new ServerSocket(0);
|
||||
int usedPort = socket.getLocalPort();
|
||||
|
||||
PortChecker checker = new PortChecker();
|
||||
boolean notFree = checker.isPortAvailable(usedPort);
|
||||
assertFalse(notFree);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void invalidPort(){
|
||||
PortChecker checker = new PortChecker();
|
||||
|
||||
assertThrows(IllegalArgumentException.class, ()-> {
|
||||
checker.isPortAvailable(-1);
|
||||
}
|
||||
);
|
||||
assertThrows(IllegalArgumentException.class, ()-> {
|
||||
checker.isPortAvailable(65536);
|
||||
}
|
||||
);
|
||||
}
|
||||
@Test
|
||||
void findFreePort() throws IOException {
|
||||
PortChecker checker = new PortChecker();
|
||||
|
||||
int port = checker.findFreePort();
|
||||
int defaultPort = 8080;
|
||||
int lastPort = 8090;
|
||||
|
||||
boolean greaterOrEqual = port >= defaultPort;
|
||||
boolean lessOrEqual = port <= lastPort;
|
||||
boolean inRange = greaterOrEqual && lessOrEqual;
|
||||
boolean isItFree = checker.isPortAvailable(port);
|
||||
|
||||
assertTrue(inRange);
|
||||
}
|
||||
@Test
|
||||
void noFreePort() {
|
||||
List<ServerSocket> notFreePorts = new ArrayList<>();
|
||||
int defaultPort = 8080;
|
||||
int lastPort = 8090;
|
||||
|
||||
try {
|
||||
for (int i = defaultPort; i <= lastPort; i++) {
|
||||
try {
|
||||
notFreePorts.add(new ServerSocket(i));
|
||||
}
|
||||
catch (IOException e) {
|
||||
}
|
||||
}
|
||||
|
||||
PortChecker checker = new PortChecker();
|
||||
assertThrows(IOException.class, () -> {
|
||||
checker.findFreePort();
|
||||
}
|
||||
);
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
for (ServerSocket s : notFreePorts) {
|
||||
try {
|
||||
s.close();
|
||||
}
|
||||
catch (IOException e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue