Home > Enterprise >  How can I reuse test implementation?
How can I reuse test implementation?

Time:09-09

I started creating JUnit tests for the different algorithms, but soon I realized that most of the time, I write the same code, so I decided to centralize those parts.

Instead of doing multiple calls to the DB, I prefer to create a mock, and read values from CSV. I mock each provider that is responsible to do the call to DB and return values.

Let's say I have the following providers: A, B, C, D, E, F.
I created for each one an abstract class on which I have some methods, one to read values from csv, another one to filter the result and use it in the when-thenReturn statement: AMock, BMock, CMock, DMock, EMock, FMock.

I know that I can't create a test that extends all these classes, so at the moment, I use this workaround:

EMock extends FMock
DMock extends EMock
CMock extends DMock
BMock extends CMock
AMock extends BMock

MyTest1 extends AMock
MyTest2 extends AMock
MyTest3 extends CMock

etc.

But I don't like it very well, because I don't need it all every time,
for example if MyTest2 needs only AMock and EMock, extending the AMock I have them all.

It's there a more elegant approach?

CodePudding user response:

Instead of inheritance I would rather use composition (dependency injection) to achieve this abstraction (reusability)

Like this:

class MyTest1 {

  private AMock aMock;

  ...
  
}

Sure you can use use inheritance to avoid duplication in BMock, CMock. etc. But even here I will rather use composition to achieve the same Goal. Generally inheritance should be used if you want to enforce some behaviour (generally through constructor and abstract method).

In your case (as far as I understand), you are more interested by the features that each mock provides independently.

In case EMock internally uses a method from BMock ... to achieve its task:

class EMock {

  private AMock aMock;
   
  private BMock aMock;

  ...
  
}

In case nothing from BMock is used in EMock:

class MyTest1 {

  private AMock aMock;

  private BMock bMock;

  ...

  private EMock eMock;

  
  // further methods where aMock.doSomeStuff() ... is called.
}
  • Related