Want to expedite tests and avoid creating mock objects for every single scenario? Here's how Fixture Factory can help.

Introduction

Running tests at every stage of software development is becoming increasingly critical. Because of this, many test frameworks are emerging to expedite the full cycle of development, from conception to software delivery.  

Setting up scenarios for testing in the development environment, however, can be a highly stressful task. In some situations, developers need to create an enormous amount of test data to cover each scenario. Furthermore, most of the test codes are related to setting up these objects.

Fixture Factory is a Java test framework that aims to reduce the need to create multiple mock objects used in testing by reusing objects in various development testing scenarios.

This article describes how we can use the Fixture Factory framework on unit and component tests for a Spring Boot project.

What Is Fixture Factory Framework?

Fixture Factory is a tool that helps us create mock objects for unit tests in Java. This framework also helps us reuse these objects, creating new fake items based on existing items. 

The base of this tool is the object template composition, where you set several rules from a template class. The syntax of a rule is: 

Fixture.of(ClassThatYouWantToMock.class).addTemplate(<Rule ID>, new Rule());

Where:  Rule ID is a string value that serves as a reference when the template is used, and the ClassThatYouWantToMock is the class that will get its mock attributes from the rule. 

Fixture Factory allows the reuse of templates by the composition and inheritance of templates, just like those used in object-oriented concepts.

For example, consider a composite class called "Subscription" that maps a database table featuring Student and Course attributes. Considering that Student and Course template rules have been created with the rule identification "VALIDSTUDENTRULEID" and "VALIDCOURSERULEID" respectively, a valid template rule for Subscription with the Student and Course rules would be:

    public void load() {
        Fixture.of(Subscription.class).addTemplate(<RuleID>, new Rule() );
    }

Using the same example, imagine that we need to create a Subscription rule almost equal to the one created above except that one attribute needs to be different from the rest of the previous template. The new template rule, with inheretance from a previous template, should be:

    public void load() {
        Fixture.of(Subscription.class).addTemplate(<ParentRuleID>, new Rule() );
        Fixture.of(Subscription.class).addTemplate(<RuleID>)
                .inherits(<ParentRuleID>, new Rule());

    }
Creating a Fixture Factory on a Spring Boot Project

Before we can implement the templates in the test scenarios, we need to install the Fixture Factory dependency on the Spring Boot project.

Installation on a Spring Boot project using Maven looks like this:

  <dependency>
       <groupId>br.com.six2six</groupId>
       <artifactId>fixture-factory</artifactId>
       <version>3.1.0</version>
   </dependency>

And a Spring Boot project using Gradle looks like this:

  testImplementation group: 'br.com.six2six', name: 'fixture-factory', version: '3.1.0'

You can also create a test source package and create all template classes on this package.

Applying Fixture Factory in a Unit Test

Once the Fixture Factory dependency is installed in the Spring Boot project, it's time to turn our attention to the template's test source package. You can create variables in test scenarios based on the template rule defined earlier. The first step to achieving this is to add an instruction to load these templates into the test class.

    @BeforeEach

    public void setup(){

        FixtureFactoryLoader.loadTemplates("<template source package>");

    }

This statement allows loading the templates by their package definition. 

Consider the subscription example. You can set a subscription variable on a test scenario with a template rule like this:

Subscription mockSubscriptionObject = Fixture.from(Subscription.class).gimme(<RuleID>);

Fixture Factory provides the customization of actions to be completed when a template rule is generated. For example, in the Subscription scenario, let's say the test unit needs to evaluate a custom query from the database. For this unit test to work as expected, the rules generated must be persisted on the test environment database. The Fixture Factory framework provides a class called "Processor" for these scenarios. In our Subscription illustration, the Processor class should be:

@Component
@Slf4j
@Transactional
public class EntityManagerProcessor implements Processor {


    private final EntityManager entityManager;


    public EntityManagerProcessor (final EntityManager entityManager){
        this.entityManager = entityManager;


    }


    @Override
    public void execute(final Object result) {
        if(result.getClass().isAnnotationPresent(Entity.class)){
            try{
                persisteCompositeClass(result);
                findOrPersist(result);
            }catch (IllegalAccessException illegalAccessException){
                log.error("Error to access the fields ",illegalAccessException);
            }


        }
    }


   private Object findOrPersist(Object result){...}


   private void persisteCompositeClass(Object result){...}


}

The usage of the Processor on the unit test scenario doesn't much change the structure of a template call:

@Autowired
private EntityManagerProcessor entityManagerProcessor;
...
Subscription mockSubscriptionObjectPersisted =  Fixture.from(Subscription.class).uses(entityManagerProcessor).gimme(<RuleID>);
Conclusion 

Fixture Factory contains functionalities that improve the organization of test code and mock object reuse on test scenarios. This framework also provides the customization of actions of generated objects, which allows the test developer to adapt the behavior of generated objects to the test project requirement.

Using Fixture Factory in a Spring Boot project is easy, and Spring Boot frameworks provide mechanisms for unit tests, integrated tests, and a mixture of both types of tests. You can use Fixture Factory with all kinds of tests in a Spring Boot project, including using the same template rule for both types of tests.

One thing to be aware of is template rule reuse: once a parent or component rule changes, the child or compound rule also changes and will likely break the test methods involved.

For more information about Fixture Factory and how to integrate it into a Spring Boot project, visit the Fixture Factory project and the Fixture Factory Spring Boot sample code project on GitHub via the links below.

 

References

fixture factory, six2six. GitHub. 

fixture factory SB sample code, masousa. GitHub.


Author

Matheus Sousa

Matheus Sousa is a Senior Software Engineer at Avenue Code. He holds a master's degree in Computer Software Engineering. He has more than 11 years of experience in software development using Java and its frameworks, and he is passionate about software development.


[JAVA 21] Structured Concurrency: Powering Data Orchestration with Virtual Threads and Scopes

READ MORE

How to Use Circuit Breaker Resilience in Your API Integration

READ MORE

How to Create Your Own RAR Extractor Using Electron

READ MORE