Skip to content
Advertisement

Stop running Java JUnit test method after predefined time without failing the test

I have a class that starts multiple threads which all run while(true) loops. Is it possible to have an Assert statements on the state of a test after it has run for a certain amount of time?

The Timeout functionality would work, if it didn’t fail the test.

This is a contrived example to show what I’m trying to do. The test is at the bottom.

    class RunProgram {

    private DataClass dataClass = new DataClass();
    private Thread1 thread1 = new Thread1(dataClass);

    void startThis() {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        try {
            pool.execute(thread1);//Thread 1
            //... more threads with while loops
            runMainThread(dataClass);
        } finally {
            pool.shutdown();
        }
    }

    void runMainThread(DataClass data1){
        while(true){
            dataClass.setInternalDataInt(20);
            //do stuff
        }
    }

    public Thread1 getThread1(){
        return this.thread1;
    }
}

class Thread1 implements Runnable{
    private DataClass dataClass;

    Thread1(DataClass dataClass){
        this.dataClass = dataClass;
    }

    public void run() {
        dataClass.setInternalDataInt(10);
        while (true) {
            //dostuff
        }
    }

    public DataClass getDataClass(){
        return dataClass;
    }

    public void setDataClass(DataClass dataClass){
        this.dataClass = dataClass;
    }
}

class DataClass {
    private int internalDataInt;
    
    public int getInternalDataInt(){
        return this.internalDataInt;
    }
    
    public void setInternalDataInt(int internalDataInt){
        this.internalDataInt = internalDataInt;
    }
}

class Tests{
    @Test
    public void stateOfThread1() {
        RunProgram runProgram = new RunProgram();
        runProgram.startThis();
        //Run above for 100 millisecond and then end
        Assertions.assertEquals(runProgram.getThread1().getDataClass().getInternalDataInt(), 20);
    }
}

Advertisement

Answer

Found what I was looking for.

Use a ScheduledExecutorService:

An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

RunProgram runProgram = new RunProgram();
ScheduledExecutorService testExecutor = Executors.newScheduledThreadPool(1);
Future future = testExecutor.submit(runProgram);
Thread.sleep(500);
future.cancel(true);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement