Search code examples
javamockitojunit4

Inheritance with JUnit


I have two classes (B & C) that extend from A.

I am trying to write a unit test in a way that I can just pass in concrete implementations of B and C and let them run. For example:

abstract class A {
  abstract doSomething();

  public static void send(A a){
      // sends a off
  }
}

class B extends A {
  public void doSomething(){
    this.send(this)
  }

class C extends A {
  public void doSomething(){
    this.send(this);
    this.write(this)
  }
  public void write(A a){
     //writes A to file
  }
}

Now, I am looking for a way to unit test this abstractly and only have to pass in implementations and let the unit test run. For example:

//setup junit testsuite info
class TestClassA {

  private A theClass;

  public void testDoSomething(){
     this.theClass.doSomething();
  }
}

 // would like to be able to do
class Runner {
   B b = new B();
   C c = new C();

   // run TestClassA with b (I know this doesnt work, but this is what I'd like to do)
   TestClassA.theClass = b;
   TestClassA.run();


   // run TestClassA with c (I know this doesnt work, but this is what I'd like to do)
   TestClassA.theClass = c;
   TestClassA.run();
}

Does anyone have any ideas on how this can be accomplished?


Solution

  • @RunWith(Parameterized.class)
    public class ATest {
        private A theClass;
    
        public ATest(A theClass) {
            this.theClass= theClass;
        }
    
        @Test
        public final void doSomething() {
            // make assertions on theClass.doSomething(theClass)
        }
    
    
        @Parameterized.Parameters
        public static Collection<Object[]> instancesToTest() {
            return Arrays.asList(
                        new Object[]{new B()},
                        new Object[]{new C()}
            );
        }
    }