views:

28

answers:

2

I had the following version of a test in JUnit 3, and I tried converting it into JUnit 4, with no success. The idea is to have a base test case, that does the actual test of an interface, say Service interface. I want to test the ServiceImpl class, using the base test case.

public abstract class ServiceBaseTest extends TestCase {

   protected Service service;
   protected abstract Service getService();

   @Override
   public void setUp() {
      service = getService();
   }

   public void testMethod(){
      //test code
   }
   ...
}

ServiceImplTest class like:

public class ServiceImplTest extends ServiceBaseTest {
   @Override
   public void setUp() {
      service = new ServiceImpl();
   }
}

I am aware that I can remove the TestCase extension and use @BeforeClass for the setup method. But the difference is that @BeforeClass requires the method setup to be static. This is tricky for me,since I can't make getService() static, because it would be conflicting with abstract keyword.

Question: Is the a clean way of implementing the alternative, using JUnit 4?

A: 

Cant you just use the @Before annotation?

Visage
@Before will execute before each @Test. I just want to setup the Service once.
walters
in JUnit3, setUp() is also called before each test. If you want to ensure that getService() is only called once, you can store the result of the call in a static field
NamshubWriter
A: 
protected static Service service = null;

@Override
public void setUp() {
   if(service == null)//Check null
      service = new ServiceImpl();
}
卢声远 Shengyuan Lu