Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Super JUnit classes with no test cases

Tags:

java

junit

I have three JUnit test classes that all had some common code, including identical setup() methods. So, I factored this code out into its own class that extends TestCase and now have the three earlier JUnit test classes extend this new class. The new super class contains no tests itself.

However, in our build, JUnit runs all the JUnit test classes, including the new super class with no tests. It gives this error:

junit.framework.AssertionFailedError: No tests found in com.acme.ControllerTest

I could get rid of this error by creating some simple test that does nothing in ControllerTest. But is there a cleaner way of fixing this?

like image 482
Paul Reiners Avatar asked Sep 05 '12 21:09

Paul Reiners


1 Answers

This works for me

JUnit 3

public abstract class BaseTest extends TestCase {

    public void setUp(){
        System.out.println("before called");
    }
}

public class Test1 extends BaseTest {

    public void test() {
        Assert.assertTrue(true);
        System.out.println("Test1");
    }   
}

public class Test2 extends BaseTest {

    public void test() {
        Assert.assertTrue(true);
        System.out.println("Test2");
    }   
}

The output I get is

before called
Test2
before called
Test1

JUnit 4

For JUnit4 you do not even need to make the base class abstract. You can just use the following

public class BaseTest {
    @Before
    public void setUp(){
        System.out.println("before called");
    }
}

public class Test1 extends BaseTest {
    @Test
    public void test() {
        Assert.assertTrue(true);
        System.out.println("Test1");
    }   
}

public class Test2 extends BaseTest {
    @Test
    public void test() {
        Assert.assertTrue(true);
        System.out.println("Test1");
    }   
}

I would strongly recommend using JUnit 4. Using annotations means that you break some of this inheritance dependency which can get confusing.

like image 158
RNJ Avatar answered Oct 16 '22 12:10

RNJ