Skip to main content

On This Page

Resolving JUnit Error: Test Class Should Have Exactly One Public Zero-Argument Constructor

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

Resolving JUnit Error: Test Class Should Have Exactly One Public Zero-Argument Constructor

JUnit 4 throws an error when a test class defines a parameterized constructor. This occurs because JUnit 4 relies on a no-argument constructor to instantiate test classes independently.

Why This Matters

JUnit 4’s design ensures test isolation by creating a new instance of the test class for each test method. A parameterized constructor breaks this process, as Java no longer generates a default constructor. This disrupts test independence, risking shared state between tests and leading to unpredictable results. The cost of this error is test failures and potential bugs in test suites.

Key Insights

  • “JUnit 4 requires exactly one public zero-argument constructor, 2025”
  • “Parameterized tests with @RunWith(Parameterized.class) for JUnit 4”
  • “JUnit 5 uses @ParameterizedTest without needing a zero-argument constructor”

Working Example

@RunWith(Parameterized.class)
public class ResolvingJUnitConstructorErrorUnitTest {
    private final int input;
    private final ResolvingJUnitConstructorError service = new ResolvingJUnitConstructorError();

    public ResolvingJUnitConstructorErrorUnitTest(int input) {
        this.input = input;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
            {2}, {3}, {4}
        });
    }

    @Test
    public void givenNumber_whenSquare_thenReturnsCorrectResult() {
        assertEquals(input * input, service.square(input));
    }
}
public class ResolvingJUnitConstructorErrorUnitTest {
    private final ResolvingJUnitConstructorError service = new ResolvingJUnitConstructorError();

    @ParameterizedTest
    @ValueSource(ints = {2, 3, 4})
    void givenNumber_whenSquare_thenReturnsCorrectResult(int input) {
        assertEquals(input * input, service.square(input));
    }
}

Practical Applications

  • Use Case: Parameterized tests in JUnit 4 using @RunWith(Parameterized.class)
  • Pitfall: Using parameterized constructors in JUnit 4 without handling them, leading to the error.

References:


Continue reading

Next article

Running Tomcat Server on Two Different Ports

Related Content