How to test different subclass instance types in unit tests?

Viewed 31

I have the following code structure and I'm trying to write tests for the Controller. I can pick a shape and cover all paths in the controller's doSomething() method. There could be several cases - happy, error, response 1, response 2, etc depending on the data that I'm passing and the validations in the Controller class.

Let's say I have 6 shapes. Now I want to test that Controller.doSomething() method can accept each of those 6 shapes. However, I don't want to try all the combinations of 6 shapes and various paths because I think that would be redundant. How should I test that Controller.doSomething() method can accept each of those 6 shapes without adding redundant tests?

interface Shape {
  void printShape();
}

class Circle implements Shape {
  public void printShape() {
      System.out.println("Printing from Circle");
  }
}

class Square implements Shape {
  public void printShape() {
      System.out.println("Printing from Square");
  }
}

class Controller {
   Service service;
   public void doSomething(Shape shape) {
       // performs validations
       service.sendData(shape);
   }
}

class Service {
   public void sendData(Shape shape) {
       // performs business logic
   }
}
1 Answers

Have you ever looked at testng’s @DataProvider ? You can set up data so you write once your test and execute it multiple times depending on the input data.

In order words you can make your tests data driven. Junit has the same feature I’m just not sure what it is called.

Related