All Posts

How to Fix JUnit Invalid test class Error

How to Fix JUnit Invalid test class Error

Exception Trace

org.junit.runners.model.InvalidTestClassError: Invalid test class ‘com.testingdocs.tutorials.TestCaseOne’:
1. The class com.testingdocs.tutorials.TestCaseOne is not public.
2. Test class should have exactly one public constructor
at org.junit.runners.ParentRunner.validate(ParentRunner.java:525)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:102)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:84)
at org.junit.runners.JUnit4.<init>(JUnit4.java:23)

 

The error message suggests that your JUnit test class has incorrect visibility or constructor issues.

JUnit Invalid Test Class

Possible Fixes

Ensure the Test Class is Public

Your test class must be declared as public:


package com.testingdocs.tutorials;

import org.junit.Test;
import static org.junit.Assert.assertTrue;

public class TestCaseOne {  // Ensure the class is public

    @Test
    public void testExample() {
        assertTrue(true);
    }
}
            

Ensure There is Only One Public Constructor

JUnit test classes should have only one public constructor. If you have multiple constructors, remove the extra ones.

Incorrect:


public class TestCaseOne {
    public TestCaseOne() {}  // Default constructor (OK)
    public TestCaseOne(String param) {}  // Extra constructor (INVALID)
}
            

Correct:


public class TestCaseOne {
    public TestCaseOne() {}  // OK
}
            

Ensure JUnit is Using the Correct Runner

If you are using JUnit 4, add the correct runner annotation:


import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TestCaseOne {
    @Test
    public void testExample() {
        assertTrue(true);
    }
}
            

For JUnit 5 (Jupiter), no runner annotation is needed:


import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class TestCaseOne {
    @Test
    void testExample() {
        assertTrue(true);
    }
}
            

Ensure the Test Class is Not a Nested (Inner) Class

If your test class is an inner class, it must be static:


public class OuterClass {
    public static class TestCaseOne {  // Must be static
        @Test
        public void testExample() {
            assertTrue(true);
        }
    }
}
            

Final Checklist

  • ✅ Class is public
  • ✅ Only one (or no) constructor
  • ✅ No extra constructor parameters
  • ✅ Proper @Test annotations
  • ✅ Using correct JUnit version

After applying these fixes, try running the test again.