Search code examples
javamaventestingjunitjunit5

class junit.framework.TestSuite cannot be cast to class org.junit.jupiter.api.Test


I am new to JAVA and Junit and trying to do something simple. I have the test passed but I see in the terminal initailizationError side this error "class junit.framework.TestSuite cannot be cast to class org.junit.jupiter.api.Test" This is the version of my Junit dependencies.

 <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.9.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <version>5.9.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>RELEASE</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>

This is the test that I am trying to run

import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;

/**
 * Unit test for simple App.
 */
public class AppTest
    extends TestCase
{
    @Test
    public void firstTest() {
        Assertions.assertEquals(2, 2);

    }

    /**
     * Create the test case
     *
     * @param testName name of the test case
     */


    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return (Test) new TestSuite( AppTest.class );
    }

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
        assertTrue( true );
    }
}

I could not understand the error as it is my first time useing it


Solution

  • I think the simplest fix is for you to delete your suite method. You don't need it, and your tests will run quite happily without it. Once you are a bit more confident and familiar with Java and JUnit, then maybe suites will help you organise and group tests, but you can certainly start without them.

    The way you are attempting to create a test suite seems to follow the approach of JUnit 3, but you are using JUnit 5. JUnit changed a lot from JUnit 3 and JUnit 4, and also from JUnit 4 to JUnit 5, so it's not surprising that something from JUnit 3 doesn't work with JUnit 5.

    I hadn't seen this way of writing test suites before, but I did find that this page talks about JUnit 5 and then presents examples using JUnit 3. To be quite frank I found the content of that page to be of poor quality and cannot recommend it. If you are using that page to learn about JUnit then I would advise you to look elsewhere.