简体   繁体   中英

Does ReflectionTestUtils works only on fields of a class, not on variables defined inside a method of that class?

Does ReflectionTestUtils works only on fields of a class, not on variables defined inside a method of that class?

I tried to test the fields of a class, it works perfectly fine using ReflectionTestUtils , if I try it on variables of a method, I get an IllegalArgumentException .

Example Code:

public class Check {
     String city;

     public void method() {
         city = "Bangalore";
         String Street = "MGRoad";
    }
}

If I want to have a JUnit tests for the above class using ReflectionTestUtils .

Check c = new Check();
assert ReflectionTestUtils.getField(c, "city").equals("Bangalore") 
-> works fine.
assert ReflectionTestUtils.getField(c, "Street").equals("MGRoad") 
-> gives illegalArgumentException.

Please have a look and suggest me if I can test the attributes of a method.

You cannot access local variables using reflection and String Street = "MGRoad"; is local variable to that method

If what you mean is variables local to methods/constructors, you can not access them with reflection. ... There is no way to obtain this information via reflection. Reflection works on method level, while local variables are on code block level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM