Bird
Raised Fist0
JUnittesting~15 mins

ParameterResolver extension in JUnit - Build an Automation Script

Choose your learning style10 modes available
Automate a JUnit test using ParameterResolver to inject a custom object
Preconditions (3)
Step 1: Create a ParameterResolver class that implements ParameterResolver interface
Step 2: Implement supportsParameter to return true for the custom object type
Step 3: Implement resolveParameter to return an instance of the custom object
Step 4: Create a test class and register the ParameterResolver extension using @ExtendWith
Step 5: Write a test method that accepts the custom object as a parameter
Step 6: Inside the test method, verify the custom object is not null and has expected properties
✅ Expected Result: The test runs successfully with the custom object injected by the ParameterResolver, and assertions pass confirming the object is correctly provided
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the injected parameter is not null
Assert that the injected parameter has expected property values
Best Practices:
Use @ExtendWith to register the ParameterResolver
Implement ParameterResolver interface correctly with supportsParameter and resolveParameter
Keep the ParameterResolver logic simple and focused
Use assertions from org.junit.jupiter.api.Assertions
Write clear and descriptive test method names
Automated Solution
JUnit
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

// Custom object to be injected
class CustomObject {
    private final String value;

    public CustomObject(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

// ParameterResolver implementation
class CustomObjectParameterResolver implements ParameterResolver {

    @Override
    public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
        return parameterContext.getParameter().getType() == CustomObject.class;
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
        return new CustomObject("InjectedValue");
    }
}

@ExtendWith(CustomObjectParameterResolver.class)
public class CustomObjectParameterResolverTest {

    @Test
    void testInjectedCustomObject(CustomObject customObject) {
        assertNotNull(customObject, "CustomObject should be injected and not null");
        assertEquals("InjectedValue", customObject.getValue(), "CustomObject value should match the injected value");
    }
}

The code defines a CustomObject class with a simple string property.

The CustomObjectParameterResolver class implements JUnit 5's ParameterResolver interface. It overrides supportsParameter to check if the parameter type is CustomObject. It overrides resolveParameter to return a new CustomObject instance with a fixed value.

The test class CustomObjectParameterResolverTest is annotated with @ExtendWith to register the resolver. The test method testInjectedCustomObject accepts a CustomObject parameter, which JUnit injects automatically using the resolver.

Assertions check that the injected object is not null and that its value matches the expected string. This confirms the ParameterResolver works correctly.

Common Mistakes - 4 Pitfalls
Not implementing supportsParameter correctly
{'mistake': 'Forgetting to register the ParameterResolver with @ExtendWith', 'why_bad': "JUnit will not apply the resolver and parameters won't be injected", 'correct_approach': 'Always annotate the test class with @ExtendWith and specify your ParameterResolver class'}
Returning null from resolveParameter
Using ParameterResolver for unsupported parameter types
Bonus Challenge

Now add data-driven testing by injecting different CustomObject instances with different values for three test runs

Show Hint

Practice

(1/5)
1. What is the main purpose of a ParameterResolver in JUnit 5?
easy
A. To define the order of test execution
B. To generate test reports after execution
C. To create mock objects for tests
D. To automatically provide values for test method parameters

Solution

  1. Step 1: Understand ParameterResolver role

    A ParameterResolver is designed to supply values to parameters of test methods automatically, so tests don't need manual setup for those parameters.
  2. Step 2: Compare with other options

    Options A, C, and D relate to other testing features but not to parameter injection.
  3. Final Answer:

    To automatically provide values for test method parameters -> Option D
  4. Quick Check:

    ParameterResolver = automatic parameter injection [OK]
Hint: ParameterResolver injects parameters automatically [OK]
Common Mistakes:
  • Confusing ParameterResolver with test ordering
  • Thinking it creates mocks automatically
  • Assuming it generates reports
2. Which two methods must a class implement to be a valid ParameterResolver in JUnit 5?
easy
A. supportsParameter and resolveParameter
B. beforeEach and afterEach
C. initialize and cleanup
D. createParameter and validateParameter

Solution

  1. Step 1: Recall ParameterResolver interface methods

    The ParameterResolver interface requires implementing supportsParameter to check if a parameter is supported, and resolveParameter to provide the value.
  2. Step 2: Eliminate incorrect method pairs

    Options A, B, and C list methods unrelated to ParameterResolver interface.
  3. Final Answer:

    supportsParameter and resolveParameter -> Option A
  4. Quick Check:

    ParameterResolver methods = supportsParameter + resolveParameter [OK]
Hint: Remember: supportsParameter checks, resolveParameter provides [OK]
Common Mistakes:
  • Confusing lifecycle methods with resolver methods
  • Using incorrect method names
  • Assuming initialization methods are required
3. Given this ParameterResolver implementation, what will be printed when the test runs?
class MyResolver implements ParameterResolver {
  public boolean supportsParameter(ParameterContext pc, ExtensionContext ec) {
    return pc.getParameter().getType() == String.class;
  }
  public Object resolveParameter(ParameterContext pc, ExtensionContext ec) {
    return "InjectedValue";
  }
}

@ExtendWith(MyResolver.class)
class TestClass {
  @Test
  void testMethod(String param) {
    System.out.println(param);
  }
}
medium
A. null
B. InjectedValue
C. Compilation error
D. Test fails with exception

Solution

  1. Step 1: Analyze supportsParameter method

    It returns true only if the parameter type is String, so the test method's String param is supported.
  2. Step 2: Analyze resolveParameter method

    It returns the string "InjectedValue", so this value will be injected into the test method parameter.
  3. Final Answer:

    InjectedValue -> Option B
  4. Quick Check:

    Parameter injection prints InjectedValue [OK]
Hint: Check supportsParameter return true for parameter type [OK]
Common Mistakes:
  • Assuming parameter is null if not supported
  • Expecting compilation error due to interface methods
  • Thinking test fails without explicit parameter value
4. Identify the error in this ParameterResolver implementation:
class FaultyResolver implements ParameterResolver {
  public boolean supportsParameter(ParameterContext pc, ExtensionContext ec) {
    return pc.getParameter().getType() == Integer.class;
  }
  public Object resolveParameter(ParameterContext pc, ExtensionContext ec) {
    return 42;
  }
}

@ExtendWith(FaultyResolver.class)
class TestClass {
  @Test
  void testMethod(int param) {
    System.out.println(param);
  }
}
medium
A. Missing @Override annotations cause runtime error
B. resolveParameter returns wrong type
C. supportsParameter checks for Integer.class but parameter is primitive int
D. Test method parameter must be Integer, not int

Solution

  1. Step 1: Check parameter type in supportsParameter

    The test method parameter is primitive int, but supportsParameter checks for Integer.class, which is the wrapper class. This causes supportsParameter to return false.
  2. Step 2: Understand consequence of mismatch

    Because supportsParameter returns false, resolveParameter is never called, so the parameter is not injected, causing test failure or default value usage.
  3. Final Answer:

    supportsParameter checks for Integer.class but parameter is primitive int -> Option C
  4. Quick Check:

    Primitive vs wrapper mismatch breaks supportsParameter [OK]
Hint: Match primitive and wrapper types carefully in supportsParameter [OK]
Common Mistakes:
  • Ignoring difference between int and Integer
  • Assuming @Override annotations are mandatory
  • Thinking resolveParameter type must differ
5. You want to create a ParameterResolver that injects a unique UUID string into any test method parameter of type String. Which implementation correctly achieves this and ensures a new UUID is generated for each test invocation?
hard
A. In resolveParameter, return UUID.randomUUID().toString() without caching
B. In supportsParameter, cache a UUID and return it for all calls
C. Return a fixed UUID string in resolveParameter for all tests
D. Generate UUID once in constructor and return it in resolveParameter

Solution

  1. Step 1: Understand requirement for unique UUID per test

    Each test invocation should get a new UUID string, so the UUID must be generated fresh every time resolveParameter is called.
  2. Step 2: Evaluate options for UUID generation

    In resolveParameter, return UUID.randomUUID().toString() without caching generates a new UUID string on each call, fulfilling the requirement. Options B, C, and D cache or fix the UUID, so they do not produce unique values per test.
  3. Final Answer:

    In resolveParameter, return UUID.randomUUID().toString() without caching -> Option A
  4. Quick Check:

    Generate UUID fresh in resolveParameter for uniqueness [OK]
Hint: Generate new UUID inside resolveParameter method [OK]
Common Mistakes:
  • Caching UUID and returning same value every time
  • Generating UUID once in constructor
  • Returning fixed string instead of UUID
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