Book Image

Mockito for Spring

By : Sujoy Acharya
Book Image

Mockito for Spring

By: Sujoy Acharya

Overview of this book

Table of Contents (12 chapters)
Mockito for Spring
About the Author
About the Reviewers

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) {