walters
walters

Reputation: 1467

Junit 3 to JUnit 4 conversion

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?

Upvotes: 1

Views: 1319

Answers (2)

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

protected static Service service = null;

@Override
public void setUp() {
   if(service == null)//Check null
      service = new ServiceImpl();
}

Upvotes: 1

pauljwilliams
pauljwilliams

Reputation: 19225

Cant you just use the @Before annotation?

Upvotes: 1

Related Questions