Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing several implementation of the same trait/interface

I program mostly in scala and java, using scalatest in scala and junit for unit testing. I would like to apply the very same tests to several implementations of the same interface/trait. The idea is to verify that the interface contract is enforced and to check Liskov substitution principle.

For instance, when testing implementations of lists, tests could include:

  • An instance should be empty, if and only if and only if it has zero size.
  • After calling clear, the size should be zero.
  • Adding an element in the middle of a list, will increment by one the index of rhs elements.
  • etc.

What are the best practices ?

like image 301
paradigmatic Avatar asked Mar 18 '10 09:03

paradigmatic


People also ask

Should you test the interface or the implementation?

Ultimately you are testing the implementation. In a simple case like you have defined, I say six of one and half a dozen of the other. Write your test cases to the interface or the implementation, as long as it tests the implementation sufficiently, the results are the same.

Can we write unit test for interface?

You can't. It has no implementation. You do want to test each and every class that implements this interface. To check that any class that implements the interface meets the expectations of the clients of that interface.

Should unit tests be in the same package?

Unit tests can be in any package. In essence they are just separate classes used to test the behaviour of the class being tested.

What is single unit testing?

Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. This testing methodology is done during the development process by the software developers and sometimes QA staff.


1 Answers

In Java/JUnit, I generally handle this by having an abstract testcase from which tests for the specific test class inherit all the tests and have a setup method instantiating the implementation. I can't watch the video abyx posted right now, but I suspect it's this general idea.

Another interesting possibility if you don't mind introducing yet another testing framework would be to use JDave Specification classes.

I haven't tried using either of these with Scalatest or with Scala traits and implementations, but it should be possible to do something similar.

like image 139
Don Roby Avatar answered Sep 23 '22 22:09

Don Roby