Janus
Janus

Reputation: 309

Extrating jUnit test methods in interface

Is it possible to declare methods in an interface with the annotation @Test and to use them in a concrete class. My problem is, that the class implementing the interface has the annotation @Override and not @Test. Is there a solution or do I have to use a parent class?

Upvotes: 2

Views: 941

Answers (1)

Ilya
Ilya

Reputation: 29731

Use abstract class instead of interface.
You can mark methods in absctract class with annotation @Test
1)

public interface ITest {
   @Test
   public void simpleTest();
} 

public class SimpleTest implements ITest
{
   @Override
   public void simpleTest()
   {
      Assert.assertTrue(true);
   }
}  

we get

Tests in error: 
  initializationError(com.company.tester.SimpleTest)  

2)

public interface ITest {

   public void simpleTest();
}  

public class SimpleTest implements ITest
{

   @Test
   @Override
   public void simpleTest()
   {
      Assert.assertTrue(true);
   }
}  

all works well, test is passed!

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 

3) Abstract class

public abstract class ATest {

   @Test
   public abstract void simpleTest();
} 

public class SimpleTest extends ATest
{
   @Override
   public void simpleTest()
   {
      Assert.assertTrue(true);
   }
}  

public class SecondTest extends ATest
{
   @Override
   public void simpleTest()
   {
      Assert.assertFalse(false);
   }
} 

tests are passed well!

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

Upvotes: 1

Related Questions