Bird
Raised Fist0
JUnittesting~20 mins

Builder pattern for test data in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Builder Pattern Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of JUnit test using Builder pattern
Given the following JUnit test code using a Builder pattern for creating test data, what will be the test result?
JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class User {
    private String name;
    private int age;

    private User(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }

    public static class Builder {
        private String name = "Default";
        private int age = 18;

        public Builder name(String name) {
            this.name = name;
            return this;
        }

        public Builder age(int age) {
            this.age = age;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }
}

public class UserTest {
    @Test
    public void testUserBuilder() {
        User user = new User.Builder()
            .name("Alice")
            .age(25)
            .build();

        assertEquals("Alice", user.getName());
        assertEquals(25, user.getAge());
    }
}
ATest fails because age is 18, not 25
BCompilation error due to missing Builder constructor
CTest fails because name is "Default", not "Alice"
DTest passes successfully
Attempts:
2 left
💡 Hint
Check how the Builder sets the fields before building the User object.
❓ assertion
intermediate
1:30remaining
Correct assertion for Builder-created object
You have a User object created by the Builder with name "Bob" and age 30. Which assertion correctly verifies the age in JUnit 5?
JUnit
User user = new User.Builder().name("Bob").age(30).build();
AassertEquals(30, user.getAge());
BassertTrue(user.getAge() == 30);
CassertEquals("30", user.getAge());
DassertFalse(user.getAge() != 30);
Attempts:
2 left
💡 Hint
Use the assertion that compares expected and actual values with correct types.
🔧 Debug
advanced
2:00remaining
Identify the bug in Builder pattern usage
What is the bug in this test code using the Builder pattern?
JUnit
User user = new User.Builder()
    .name(null)
    .age(22)
    .build();

assertEquals("John", user.getName());
AThe test expects name "John" but Builder sets name to null
BBuilder does not initialize age, causing NullPointerException
CUser class constructor is missing, causing NullPointerException
DassertEquals cannot compare null values, causing NullPointerException
Attempts:
2 left
💡 Hint
Check what value the Builder sets for name and what the test expects.
🧠 Conceptual
advanced
1:30remaining
Why use Builder pattern for test data?
Which is the best reason to use the Builder pattern when creating test data objects in automated tests?
AIt automatically generates test reports after each test
BIt allows creating complex objects with readable code and optional parameters
CIt replaces the need for assertions in tests
DIt ensures tests run faster by caching objects
Attempts:
2 left
💡 Hint
Think about how Builder helps with object creation in tests.
❓ framework
expert
2:30remaining
Integrating Builder pattern with JUnit 5 parameterized tests
How can you use the Builder pattern to supply different User objects to a JUnit 5 parameterized test?
JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.Stream;

public class UserTest {

    static Stream<User> userProvider() {
        return Stream.of(
            new User.Builder().name("Anna").age(20).build(),
            new User.Builder().name("Ben").age(35).build()
        );
    }

    @ParameterizedTest
    @MethodSource("userProvider")
    void testUserAges(User user) {
        assertTrue(user.getAge() > 18);
    }
}
AMethodSource must return Strings, not User objects
BBuilder pattern cannot be used with parameterized tests
CThis code correctly uses Builder objects as parameters for the test
DParameterizedTest requires @ValueSource, not @MethodSource
Attempts:
2 left
💡 Hint
Check if the method source returns the correct type for the test parameter.

Practice

(1/5)
1. What is the main benefit of using the Builder pattern for test data in JUnit tests?
easy
A. It automatically runs tests faster without code changes.
B. It generates random test data without any setup.
C. It replaces the need for assertions in tests.
D. It creates test data with clear, readable, and flexible code.

Solution

  1. Step 1: Understand Builder pattern purpose

    The Builder pattern helps create objects step-by-step with readable code.
  2. Step 2: Relate to test data creation

    Using Builder for test data makes tests clearer and easier to maintain by avoiding repeated setup code.
  3. Final Answer:

    It creates test data with clear, readable, and flexible code. -> Option D
  4. Quick Check:

    Builder pattern = clear, flexible test data [OK]
Hint: Builder pattern improves test data clarity and flexibility [OK]
Common Mistakes:
  • Thinking Builder speeds up test execution
  • Believing Builder removes need for assertions
  • Confusing Builder with random data generation
2. Which of the following is the correct way to start a Builder for a User object in JUnit?
easy
A. User user = User.builder().setName("Alice").build();
B. User user = new User.Builder().setName("Alice").build();
C. User user = new User().builder().setName("Alice").build();
D. User user = User.build().setName("Alice").builder();

Solution

  1. Step 1: Identify common Builder syntax

    Usually, Builder is started with a static method like builder() on the class.
  2. Step 2: Check method chaining order

    Correct chaining is User.builder().setName(...).build(). User user = User.builder().setName("Alice").build(); matches this.
  3. Final Answer:

    User user = User.builder().setName("Alice").build(); -> Option A
  4. Quick Check:

    Static builder() method starts Builder [OK]
Hint: Start Builder with ClassName.builder() static method [OK]
Common Mistakes:
  • Using new User.Builder() instead of User.builder()
  • Calling builder() on an instance instead of class
  • Mixing build() and builder() order
3. Given this Builder code snippet, what will be the value of user.getAge()?
var user = User.builder()
  .setName("Bob")
  .setAge(30)
  .setAge(25)
  .build();
medium
A. 30
B. 25
C. null
D. Compilation error

Solution

  1. Step 1: Analyze method calls order

    The Builder sets age first to 30, then overwrites it to 25 before build.
  2. Step 2: Understand final value assignment

    The last call to setAge(25) overwrites previous age, so final age is 25.
  3. Final Answer:

    25 -> Option B
  4. Quick Check:

    Last setter call wins = 25 [OK]
Hint: Last setter call overwrites previous value [OK]
Common Mistakes:
  • Assuming first setAge value remains
  • Thinking Builder merges values
  • Expecting compilation error due to repeated setters
4. Identify the error in this Builder usage for a Product test data:
var product = Product.builder()
  .setName("Book")
  .setPrice(-10)
  .build();
medium
A. Negative price should be rejected or cause error.
B. Missing call to build() method.
C. Builder must be created with new keyword.
D. setName() cannot be called before setPrice().

Solution

  1. Step 1: Check Builder method calls

    Builder calls setName, setPrice, then build() correctly.
  2. Step 2: Validate data correctness

    Price is set to -10, which is invalid for product price and should be rejected or throw error.
  3. Final Answer:

    Negative price should be rejected or cause error. -> Option A
  4. Quick Check:

    Invalid data in Builder = error [OK]
Hint: Check for invalid data values in Builder calls [OK]
Common Mistakes:
  • Thinking build() call is missing
  • Assuming new keyword is required for Builder
  • Believing setter order matters
5. You want to create multiple Order test objects with different status but same customerId and amount. How can you best use the Builder pattern to avoid repeating common fields?
hard
A. Use static variables for common fields and set status directly on Order after build.
B. Write separate Builder calls fully for each Order with all fields repeated.
C. Create a base Builder with common fields, then clone and set different statuses before build.
D. Create Orders with default constructor and set fields manually without Builder.

Solution

  1. Step 1: Identify repeated data in test objects

    customerId and amount are same for all Orders; status differs.
  2. Step 2: Use Builder cloning or base setup

    Create a base Builder setting common fields, then clone or copy it to set different statuses before building each Order.
  3. Final Answer:

    Create a base Builder with common fields, then clone and set different statuses before build. -> Option C
  4. Quick Check:

    Reuse Builder base to avoid repetition [OK]
Hint: Reuse Builder base, change only differing fields [OK]
Common Mistakes:
  • Repeating all fields in each Builder call
  • Setting fields after build instead of in Builder
  • Avoiding Builder and using manual setters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard