Search code examples
javajunitjava-threads

How to set values to private variable in class where class constructor itself starting the thread?


Below is my source code class where class constructor starting the thread.But in run() it is checking for not null value of a varible.So in order to test the using junit that variable should not be null.

public class MainClass extends Thread {
    private SomeQue que;
    private static final String THREAD_NAME = "s_thread";
    private boolean isRunning = false;

    public MainClass () {
        setName(THREAD_NAME);
        setIsRunning(true);
        start();
    }

    public void run() {
        while (isRunning()) {
            if (que!= null) {
                obj = que.pop();
                if (obj != null) {
                    //....
                }
            }
        }
    }
}

If use

ReflectioinTerstUtils.setField(new MainClass(),"que",que);      

we have to create the object to set data to variable to while creating object itself thread is getting started.So any ideas..


Solution

  • The only way I see around this (besides refactoring) is to create an instance of the object without calling the constructor. This can be done using the internal class sun.misc.Unsafe:

    Note: the very name of this class tells you how powerful (and deadly) it can be. With great power comes great responsibility. Use wisely.

    // Obtain the unsafe object without throwing a SecurityException (assuming no security manager)
    Field field = Unsafe.class.getDeclaredField("theUnsafe");
    field.setAccessible(true);
    Unsafe unsafe = (Unsafe) field.get(null);
    
    // Create the instance 
    MainClass instance = (MainClass) unsafe.allocateInstance(MainClass.class); // Constructor is not called
    
    // set isRunning if needed
    // do junit stuff