I have a class.
I initialize a variable in the constructor of that class.
I call a method that contains a while loop and increments the variable each time through.
I wrote a test to check the value of the variable after the method has been called (and goes through the while loop one time).
public class ThreadGenerator implements Runnable {
private int requests;
private int limit;
public ThreadGenerator() {
requests = 0;
}
public void setRequestLimit(int anyLimit) {
this.limit = anyLimit;
}
public void generateThread() {
new Thread(this).start();
}
public void run() {
while(requests < limit) {
try {
// do some stuff
requests++;
// close some stuff
} catch (IOException e) {
e.printStackTrace();
}
}
}
public int getRequests() {
return requests; // calling this method from my tests always returns 0
}
In my test, when I create a new instance of this class, then call this method on that class, it runs correctly and it increments the request counter correctly. I’ve tried several print statements to make sure of that. But if I call getRequests on my ThreadGenerator object in my test, it will return 0, the amount it was initialized with.
My test code:
ThreadGenerator threadGenerator = new ThreadGenerator();
threadGenerator.setRequestLimit(1);
threadGenerator.generateThread();
assertEquals(threadGenerator.getRequests(), 1);
How can I modify this variable I initialized in the constructor and gain access to it in my test suite?
Bear in mind that just because you ask Java to create a new thread with a Runnable, doesn’t mean that the
run()method will be called immediately. It’s likely the case that theassertEqualsis happening before therunhappens the first time.You may want to return the thread and call
joinin the test on the generated thread, which will ensure that the Thread runs until it dies, possibly with a short timeout.Side note: Consider
AtomicIntegerfor your requests class, if multiple threads might modifyrequests. This will help prevent two different threads from both modifyingrequestsand overwriting one another.