0
0
JUnittesting~15 mins

Argument conversion in JUnit - Build an Automation Script

Choose your learning style9 modes available
Test argument conversion in JUnit parameterized test
Preconditions (2)
Step 1: Create a parameterized test method that accepts a String argument
Step 2: Use @ConvertWith annotation to convert the String argument to a custom type
Step 3: Provide test data as strings
Step 4: Run the test method with converted arguments
Step 5: Verify the converted argument is correctly transformed inside the test
✅ Expected Result: The test runs successfully with the argument converted from String to the custom type, and assertions pass confirming correct conversion
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the converted argument matches expected values
Best Practices:
Use @ParameterizedTest with @ValueSource for input strings
Implement a custom ArgumentConverter class
Use @ConvertWith annotation on the test method parameter
Keep test methods clear and focused
Use assertions from org.junit.jupiter.api.Assertions
Automated Solution
JUnit
import org.junit.jupiter.api.Assertions;
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 org.junit.jupiter.params.provider.ValueSource;

class Temperature {
    private final double celsius;

    public Temperature(double celsius) {
        this.celsius = celsius;
    }

    public double getCelsius() {
        return celsius;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Temperature other = (Temperature) obj;
        return Double.compare(other.celsius, celsius) == 0;
    }

    @Override
    public int hashCode() {
        return Double.hashCode(celsius);
    }
}

class TemperatureConverter implements ArgumentConverter {
    @Override
    public Object convert(Object source, java.lang.reflect.Parameter context) throws ArgumentConversionException {
        if (!(source instanceof String)) {
            throw new ArgumentConversionException("Can only convert from String");
        }
        String str = (String) source;
        try {
            // Assume input like "36.5C" - remove 'C' and parse double
            if (!str.endsWith("C")) {
                throw new ArgumentConversionException("String must end with 'C'");
            }
            double value = Double.parseDouble(str.substring(0, str.length() - 1));
            return new Temperature(value);
        } catch (NumberFormatException e) {
            throw new ArgumentConversionException("Invalid temperature format", e);
        }
    }
}

public class ArgumentConversionTest {

    @ParameterizedTest
    @ValueSource(strings = {"36.5C", "0C", "100C"})
    void testTemperatureConversion(@ConvertWith(TemperatureConverter.class) Temperature temp) {
        Assertions.assertNotNull(temp);
        // Check that the celsius value matches expected values
        String input = temp.getCelsius() + "C";
        Assertions.assertTrue(input.endsWith("C"));
    }
}

This test uses JUnit 5's parameterized test feature with @ValueSource to provide string inputs representing temperatures.

The TemperatureConverter class implements ArgumentConverter to convert the input string (like "36.5C") into a Temperature object by parsing the numeric part.

The test method testTemperatureConversion uses @ConvertWith to apply this converter to the parameter. Inside the test, assertions check that the converted object is not null and that the value ends with 'C', confirming correct conversion.

This approach keeps the test clean and focused on verifying argument conversion works as expected.

Common Mistakes - 4 Pitfalls
{'mistake': 'Not implementing ArgumentConverter interface correctly', 'why_bad': "The converter won't be recognized or will throw errors during test execution", 'correct_approach': 'Implement the convert method properly and handle exceptions to provide clear error messages'}
Using raw strings in test without conversion
Not validating input format inside converter
Hardcoding assertions without considering converted object properties
Bonus Challenge

Now add data-driven testing with 3 different temperature string inputs including edge cases like negative and zero values

Show Hint