JUnit General Testing Class

I wrote the MyInterface interface, which will be implemented by different developers.

I also wrote the MyInterfaceTest class, which contains common test methods that all developers should be able to use to test their implementations.

I just don't know how to make it work as a JUnit test.

I currently have something like this:

 public class MyInterfaceTest { private static MyInterface theImplementationToTest = null; @BeforeClass public static void setUpBeforeClass() throws Exception { // put your implementation here: theImplementationToTest = new Implementation(...); } @AfterClass public static void tearDownAfterClass() throws Exception { theImplementationToTest = null; } @Test public void test1() { /* uses theImplementationToTest */ } @Test public void test2() { /* uses theImplementationToTest */ } } 

I use the static setUpBeforeClass method because it takes a long time to initialize each implementation, so I want to initialize it once for all tests.

In this test version, developers must modify the setUpBeforeClass code and place their own implementation.

I am sure there is another way to write MyInterfaceTest , so developers will only need to inherit it or send it a parameter, and not change the code. However, I'm not experienced enough at JUnit to get it to work. Could you show me how to do this?

+7
source share
2 answers

You can subclass only the before class method and inherit all the tests.

 import org.junit.*; public class ImplementingClassTest extends MyInterfaceTest { @BeforeClass public static void setUpBeforeClass() throws Exception { // put your implementation here: theImplementationToTest = new MyInterfaceImpl(); } } 

This makes the abstract class you write look like this:

 import org.junit.*; public abstract class MyInterfaceTest { protected static MyInterface theImplementationToTest = null; @AfterClass public static void tearDownAfterClass() throws Exception { theImplementationToTest = null; } @Test public void test1() { /* uses theImplementationToTest */ } @Test public void test2() { /* uses theImplementationToTest */ } } 

Typically, you should make the method subclassed in order to implement the abstract. It is not possible to do this here because it is a static installation method. (In addition, you may want to reorganize the instances so that they do not take up much time, as this is often an anti-pattern).

+6
source

You should load the jar junit-4.10.jar and add it to your project. Then let your MyInterfaceTest class inherit a class called TestCase , for example, the public class MyInterfaceTest extends TestCase .

-3
source

All Articles