I'm having trouble finding a way to unit test some code that uses multiple threads. Below is the code that is giving me problems:
public class ThreadHandler {
private ExecutorService executorService;
private boolean isFinished = false;
public void start() {
isFinished = false;
executorService = Executors.newFixedThreadPool(10);
}
public void stop() {
isFinished = true;
executorService.shutdown();
}
public void listen(final ServerSocket serverSocket) throws IOException {
Runnable runnable = new Runnable() {
@Override
public void run() {
Socket socket = null;
try {
while (!isFinished) {
socket = serverSocket.accept();
executorService.submit(new ClassIWantToMockOut(socket));
}
} catch (IOException e) {
...
} finally {
try {
socket.close();
} catch(IOException e) {
...
}
}
}
};
this.createThread(runnable);
}
public void createThread(Runnable runnable) {
Thread serverThread = new Thread(runnable);
serverThread.start();
}
}
I would like to test the listen method by mocking out ClassIWantToMockOut(socket). As far as I've read, though, it is not possible to mock a class constructor. Is there anything I could do to make this code more unit test friendly?
Aucun commentaire:
Enregistrer un commentaire