Reputation: 1033
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?
Upvotes: 2
Views: 2893
Reputation: 1033
@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()}
);
}
}
Upvotes: 3
Reputation: 6667
I renamed your TestClassA class to MyController, since it sounds like the MyController is a part of the system under test. With that, you can test it with your B and C classes like this:
public class HelloContTest {
@Test
public void testSomethingWithB() throws Exception {
MyController controller = new MyController();
controller.setTheClass(new B());
controller.doSomething();
}
@Test
public void testSomethingWithC() throws Exception {
MyController controller = new MyController();
controller.setTheClass(new C());
controller.doSomething();
}
}
Upvotes: -1