简体   繁体   中英

How can I reuse test implementation?

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?

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

Like this:

class MyTest1 {

  @Mock
  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 use if the 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 provide independently.

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

class EMock {

  @Mock
  private AMock aMock;
   
  @Mock
  private BMock aMock;

  ...
  
}

In case nothing from BMock is used in EMock:

class MyTest1 {

  @Mock
  private AMock aMock;

  @Mock
  private BMock bMock;

  ...

  @Mock
  private EMock eMock;

  
  // futher methods where aMock.doSomeStuff() ... is called.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM