0
0
JUnittesting~5 mins

Dummy objects in JUnit

Choose your learning style9 modes available
Introduction

Dummy objects are simple placeholders used in tests when a parameter is needed but not actually used. They help keep tests clean and focused.

When a method requires an object parameter but the test does not use it.
When you want to satisfy method signatures without adding test complexity.
When you want to isolate the part of the code you are testing from unrelated dependencies.
Syntax
JUnit
SomeClass dummy = new SomeClass();

Dummy objects are usually empty or have minimal implementation.

They do not affect the test outcome but fulfill method requirements.

Examples
A dummy list passed to a method that requires a list but does not use it.
JUnit
List<String> dummyList = new ArrayList<>();
A dummy user object created to satisfy a method parameter.
JUnit
User dummyUser = new User();
Sample Program

This test uses a dummy User object to call the process method. The dummy object is empty but satisfies the method parameter requirement.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;

class Service {
    public boolean process(User user) {
        // Only checks if user is not null
        return user != null;
    }
}

class User {
    // Empty dummy class
}

public class DummyObjectTest {
    @Test
    void testProcessWithDummyUser() {
        Service service = new Service();
        User dummyUser = new User(); // Dummy object
        assertTrue(service.process(dummyUser));
    }
}
OutputSuccess
Important Notes

Dummy objects should not contain logic or affect test results.

They are different from mocks or stubs which simulate behavior.

Summary

Dummy objects are simple placeholders used to fill method parameters.

They keep tests clean by avoiding unnecessary complexity.

Use dummy objects when the parameter is required but not used in the test.