Bird
Raised Fist0
JUnittesting~20 mins

Argument conversion in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Argument Conversion Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of JUnit parameterized test with argument conversion
Consider the following JUnit 5 parameterized test using a custom argument converter. What will be the output when the test runs?
JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.converter.ArgumentConversionException;
import org.junit.jupiter.params.converter.ArgumentConverter;
import org.junit.jupiter.params.converter.ConvertWith;
import static org.junit.jupiter.api.Assertions.*;

class Temperature {
    private final double celsius;
    Temperature(double celsius) { this.celsius = celsius; }
    double getCelsius() { return celsius; }
}

class TemperatureConverter implements ArgumentConverter {
    @Override
    public Object convert(Object source, java.lang.reflect.Parameter context) throws ArgumentConversionException {
        if (source instanceof String s) {
            try {
                double f = Double.parseDouble(s);
                return new Temperature((f - 32) * 5 / 9);
            } catch (NumberFormatException e) {
                throw new ArgumentConversionException("Invalid temperature format");
            }
        }
        throw new ArgumentConversionException("Unsupported source type");
    }
}

public class TempTest {
    @ParameterizedTest
    @org.junit.jupiter.params.provider.ValueSource(strings = {"32", "212", "100"})
    void testFreezingAndBoiling(@ConvertWith(TemperatureConverter.class) Temperature temp) {
        assertTrue(temp.getCelsius() >= 0 && temp.getCelsius() <= 100);
    }
}
ATest fails with NumberFormatException.
BTest fails with AssertionError for input "100".
CTest throws ArgumentConversionException for input "100".
DAll tests pass successfully.
Attempts:
2 left
💡 Hint
Think about the conversion formula and the assertion range.
❓ assertion
intermediate
1:30remaining
Correct assertion for converted argument in JUnit test
Given a JUnit parameterized test that converts a String to an Integer using a custom converter, which assertion correctly verifies the integer is positive?
JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.converter.ConvertWith;
import static org.junit.jupiter.api.Assertions.*;

class PositiveIntegerConverter implements org.junit.jupiter.params.converter.ArgumentConverter {
    @Override
    public Object convert(Object source, java.lang.reflect.Parameter context) {
        return Integer.parseInt(source.toString());
    }
}

public class NumberTest {
    @ParameterizedTest
    @org.junit.jupiter.params.provider.ValueSource(strings = {"5", "10", "-3"})
    void testPositive(@ConvertWith(PositiveIntegerConverter.class) Integer number) {
        // Which assertion is correct here?
    }
}
AassertTrue(number > 0);
BassertFalse(number <= 0);
CassertEquals(true, number > 0);
DassertNotNull(number);
Attempts:
2 left
💡 Hint
Choose the assertion that directly checks positivity clearly and simply.
🔧 Debug
advanced
2:00remaining
Identify the cause of ArgumentConversionException in JUnit test
This JUnit parameterized test throws ArgumentConversionException at runtime. What is the most likely cause?
JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.converter.ArgumentConverter;
import org.junit.jupiter.params.converter.ArgumentConversionException;
import org.junit.jupiter.params.converter.ConvertWith;

class BooleanStringConverter implements ArgumentConverter {
    @Override
    public Object convert(Object source, java.lang.reflect.Parameter context) throws ArgumentConversionException {
        if (source instanceof String s) {
            if (s.equalsIgnoreCase("true")) return Boolean.TRUE;
            if (s.equalsIgnoreCase("false")) return Boolean.FALSE;
            throw new ArgumentConversionException("Invalid boolean string");
        }
        throw new ArgumentConversionException("Unsupported source type");
    }
}

public class BoolTest {
    @ParameterizedTest
    @org.junit.jupiter.params.provider.ValueSource(strings = {"true", "false", "yes"})
    void testBoolean(@ConvertWith(BooleanStringConverter.class) Boolean value) {
        assertNotNull(value);
    }
}
AThe converter does not support Boolean type as target.
BThe test method signature is missing @Test annotation.
CThe input "yes" is not handled by the converter, causing ArgumentConversionException.
DThe assertion assertNotNull(value) fails for input "false".
Attempts:
2 left
💡 Hint
Check which input strings the converter accepts.
❓ framework
advanced
1:30remaining
Best practice for argument conversion in JUnit 5 parameterized tests
Which practice is recommended when implementing a custom ArgumentConverter in JUnit 5?
AReturn null silently if conversion input is invalid.
BThrow ArgumentConversionException with a clear message when conversion fails.
CCatch all exceptions and return a default value without notifying the test.
DUse System.exit() to stop tests on conversion failure.
Attempts:
2 left
💡 Hint
Think about how JUnit reports conversion errors.
🧠 Conceptual
expert
2:00remaining
Effect of argument conversion failure on JUnit 5 parameterized test execution
If a custom ArgumentConverter throws ArgumentConversionException for one parameter value in a JUnit 5 parameterized test, what happens to the test execution?
AOnly the test case with the failing parameter is skipped; other parameter values are tested.
BJUnit retries the conversion automatically until it succeeds or times out.
CThe test passes but logs a warning about the conversion failure.
DThe test run fails immediately and no further parameter values are tested.
Attempts:
2 left
💡 Hint
Consider how JUnit handles parameterized test failures per argument.

Practice

(1/5)
1. What is the main purpose of using @ConvertWith in JUnit parameterized tests?
easy
A. To generate random test data automatically
B. To skip certain test cases during execution
C. To convert input arguments to the required test method parameter types
D. To log test execution details

Solution

  1. Step 1: Understand the role of argument conversion

    Argument conversion changes input data into the type needed by the test method parameters.
  2. Step 2: Identify the purpose of @ConvertWith

    The @ConvertWith annotation tells JUnit which converter class to use to transform the input argument.
  3. Final Answer:

    To convert input arguments to the required test method parameter types -> Option C
  4. Quick Check:

    Argument conversion = convert input arguments [OK]
Hint: Remember: @ConvertWith changes input type for tests [OK]
Common Mistakes:
  • Thinking @ConvertWith skips tests
  • Confusing conversion with logging
  • Assuming it generates test data
2. Which of the following is the correct way to declare a custom argument converter class in JUnit?
easy
A. public class MyConverter extends SimpleArgumentConverter { ... }
B. public class MyConverter implements ConverterInterface { ... }
C. public class MyConverter extends ConverterBase { ... }
D. public class MyConverter implements ArgumentConverter { ... }

Solution

  1. Step 1: Recall JUnit's recommended base class for converters

    JUnit provides SimpleArgumentConverter as a base class to extend for custom converters.
  2. Step 2: Match the correct class declaration

    The correct syntax is to extend SimpleArgumentConverter, not implement interfaces or extend unknown classes.
  3. Final Answer:

    public class MyConverter extends SimpleArgumentConverter { ... } -> Option A
  4. Quick Check:

    Extend SimpleArgumentConverter = correct converter class [OK]
Hint: Custom converters extend SimpleArgumentConverter class [OK]
Common Mistakes:
  • Implementing ArgumentConverter interface directly
  • Extending non-existent base classes
  • Using wrong interface names
3. Given the following code snippet, what will be the output when the test runs?
@ParameterizedTest
@ValueSource(strings = {"42"})
void testWithConversion(@ConvertWith(MyConverter.class) Integer number) {
    System.out.println(number + 8);
}

public class MyConverter extends SimpleArgumentConverter {
    @Override
    protected Object convert(Object source, Class targetType) {
        return Integer.parseInt(source.toString());
    }
}
medium
A. 50
B. 42
C. Compilation error
D. Runtime exception

Solution

  1. Step 1: Understand the conversion process

    The string "42" is converted to Integer 42 by MyConverter using Integer.parseInt.
  2. Step 2: Calculate the printed output

    The test method adds 8 to the converted Integer 42, resulting in 50 printed.
  3. Final Answer:

    50 -> Option A
  4. Quick Check:

    42 + 8 = 50 [OK]
Hint: Convert string to int, then add 8 for output [OK]
Common Mistakes:
  • Assuming no conversion happens
  • Expecting string concatenation instead of addition
  • Thinking code causes errors
4. Identify the error in this custom converter code:
public class MyConverter extends SimpleArgumentConverter {
    @Override
    protected Object convert(Object source, Class targetType) {
        if (targetType != Integer.class) {
            throw new IllegalArgumentException("Conversion only supports Integer");
        }
        return source;
    }
}
medium
A. The method should return Integer, not Object
B. The source is returned without converting to Integer
C. The targetType check should use equals() method
D. The class should implement ArgumentConverter interface

Solution

  1. Step 1: Analyze the convert method's return value

    The method returns source directly, which is a String, not converted to Integer.
  2. Step 2: Identify the missing conversion

    It should parse the source string to Integer before returning, e.g., Integer.parseInt(source.toString()).
  3. Final Answer:

    The source is returned without converting to Integer -> Option B
  4. Quick Check:

    Return value must be converted type [OK]
Hint: Always convert source to target type before returning [OK]
Common Mistakes:
  • Returning source without conversion
  • Using != instead of equals() for class check (less critical)
  • Confusing return type requirements
5. You want to write a parameterized test that accepts a CSV string like "John,25,true" and converts it into a custom Person object with fields name (String), age (int), and active (boolean). Which approach correctly uses argument conversion in JUnit?
hard
A. Use @ValueSource(strings = {"John,25,true"}) and parse CSV inside the test method manually
B. Use @CsvSource with three separate parameters and no converter
C. Create a converter implementing ArgumentProvider and use @ArgumentsSource annotation
D. Create a converter extending SimpleArgumentConverter that splits the CSV and constructs Person; annotate parameter with @ConvertWith using this converter

Solution

  1. Step 1: Understand the need for custom conversion

    The input is a single CSV string that must be converted into a Person object before the test runs.
  2. Step 2: Identify the correct use of @ConvertWith

    Creating a converter extending SimpleArgumentConverter that parses the CSV and returns a Person object, then annotating the test parameter with @ConvertWith, is the proper approach.
  3. Final Answer:

    Create a converter extending SimpleArgumentConverter that splits the CSV and constructs Person; annotate parameter with @ConvertWith using this converter -> Option D
  4. Quick Check:

    Custom converter + @ConvertWith = correct approach [OK]
Hint: Use @ConvertWith with a converter that builds Person from CSV [OK]
Common Mistakes:
  • Parsing CSV inside test method instead of converter
  • Using wrong annotation like @ArgumentsSource
  • Passing multiple parameters without conversion
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