Using ReflectionTestUtils

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:

  • ORM frameworks, such as JPA and Hibernate, condone private or protected field access as opposed to public setter methods for properties in a domain entity
  • Spring's support for annotations such as @Autowired, @Inject, and @Resource, which provide dependency injections for private or protected fields, setter methods, and configuration methods

The following example demonstrates the capabilities of ReflectionUtils:

  1. Create a 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.

  2. The following test class invokes the 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.61