0
0
JUnittesting~15 mins

Dummy objects in JUnit - Build an Automation Script

Choose your learning style9 modes available
Use dummy objects to satisfy method parameters in unit test
Preconditions (2)
Step 1: Create a dummy object to pass as a parameter to a method that requires an object but does not use it
Step 2: Write a unit test for Calculator.add method that requires a dummy object parameter
Step 3: Call the add method with two integers and the dummy object
Step 4: Verify the add method returns the correct sum
✅ Expected Result: The test passes successfully, confirming the add method works and the dummy object satisfies the parameter requirement without affecting the test
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the add method returns the correct sum
Best Practices:
Use dummy objects only to fill parameters not used in the test
Keep dummy objects simple and minimal
Use @Test annotation for test methods
Use assertions from org.junit.jupiter.api.Assertions
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class Calculator {
    // Method that requires a dummy object parameter but does not use it
    public int add(int a, int b, Object dummy) {
        return a + b;
    }
}

public class CalculatorTest {

    // Dummy object class
    static class DummyObject {}

    @Test
    void testAddWithDummyObject() {
        Calculator calculator = new Calculator();
        DummyObject dummy = new DummyObject(); // dummy object to satisfy parameter

        int result = calculator.add(5, 7, dummy);

        assertEquals(12, result, "The add method should return the sum of two numbers");
    }
}

This test shows how to use a dummy object to satisfy a method parameter that is not used in the logic. The Calculator.add method requires three parameters, but the third parameter is not used. We create a simple DummyObject class and pass an instance to the method. The test asserts that the sum is correct, ignoring the dummy object. This keeps the test focused and simple.

Common Mistakes - 3 Pitfalls
Using a real object with complex behavior instead of a simple dummy
Not using @Test annotation on the test method
Asserting on the dummy object instead of the actual method result
Bonus Challenge

Now add data-driven testing with 3 different pairs of integers to test the add method with dummy objects

Show Hint