This is the first time am trying to use reflection for unit testing and I had this doubt.
Class Example {
public static Map<Something, Something> someMethod()
{
int temp = -1;
//Some implementation which might change the value of temp
//depending on other cases
if(temp == -1)
//Do something and return something
else
//return null
}
}
Now in the above snippet, I can get the initial value of the variable temp using reflection. I wanted to know, if the value of the variable changes while execution of the code how can I get the new value of temp? Am a total newbie to reflection so if this sounds silly please tolerate.
P.S The actual code am testing is not such a simple one. I have a feeling that I cannot unit test the last if condition without using reflection or powermock.
You cannot use reflection to access the state of a local variable. Instance variables yes, static variables yes, local variables no.
Also, as @platzhirsch notes, reflection does not allow you to attach triggers to variables of any kind. That kind of thing requires bytecode modification of some kind. However, unit testing doesn’t require triggers. Examination of values before and after should be sufficient.
I think your real problem here is that your classes have not been designed to make unit testing easy. Firstly you’ve got a static method, and they are hard to “mock”. Secondly, it appears that the logic you are trying to test is embedded inside a method. It would be much easier if (for example)
tempwas an instance variable, or the code in the// Some implementation ...was a method that you could mock.By the way, your use of the term “private” is misleading in this context. Most Java programmers would interpret “private” as meaning a static or instance variable with the
privatemodifier. But your example hastempdeclared as a local variable, for and theprivatemodifier is not allowed for local variables.