The org.springframework.test.util
package contains ReflectionTestUtils
, which is a collection of reflection-based utility methods to set a non-public field or invoke a private/protected setter method when testing the application code, as follows:
@Autowired
, @Inject
, and @Resource
, which provide dependency injections for private or protected fields, setter methods, and configuration methodsThe following example demonstrates the capabilities of ReflectionUtils
:
Secret
class in the com.packt.testutils
package with a private String field, secret
, and a public method, initiate
, to encrypt a String and set it to secret
. The following is the class:package com.packt.testutils; public class Secret { private String secret; public void initiate(String key) { this.secret = key.replaceAll("a", "z") .replaceAll("i", "k"); } }
The initiate
method replaces all the instances of a
with z
and all the instances of i
with k
. So, if you pass aio
to the method, zko
will be set to secret
.
getField
and setField
methods of ReflectionUtils
to access the private field of the Secret
class:package com.packt.testutils; import static org.junit.Assert.*; import java.lang.reflect.Field; import org.junit.Test; import org.springframework.util.ReflectionUtils; public class ReflectionUtilsTest { @Test public void private_field_access() throws Exception { Secret myClass = new Secret(); myClass.initiate("aio"); Field secretField = ReflectionUtils.findField(Secret.class, "secret", String.class); assertNotNull(secretField); ReflectionUtils.makeAccessible(secretField); assertEquals("zko", ReflectionUtils.getField(secretField, myClass)); ReflectionUtils.setField(secretField, myClass, "cool"); assertEquals("cool", ReflectionUtils.getField(secretField, myClass)); } }
First, it finds the secret
field and makes it accessible; then, it calls the getField
method to access the private
field value, and finally the setField
method is called to set a new value to the private
field.
3.133.133.61