0

I am thinking about code reuse here:

Assuming we have such classes:

 public abstract class AbstractMap {
    public abstract void put(K k, V v);
    public abstract V get(K k);
 }

 public class ConcreteMapA extends AbstractMap {
    @Override
    public void put(K k, V v) {
       // put implementation detail A
       ...
    }
    @Override
    public V get(K k) {
       // get implementation detail A
       ...
    }
 }

 public class ConcreteMapB extends AbstractMap {
    @Override
    public void put(K k, V v) {
       // put implementation detail B
       ...
    }
    @Override
    public V get(K k) {
       // get implementation detail B
       ...
    }
 }

The two maps are implementing the same functionalities but with different implementation details. I would like to write unit test for these two concrete classes. But then the test cases start to be duplicate.

 public class ConcreteMapATest {
    @Test
    public void testPutCase1 {          
       ...
    }
    @Test
    public void testPutCase2 {          
       ...
    }
    @Test
    public void testGetCase1 {         
       ...
    }
    ...
 }

 // following starts to be duplicate code
 public class ConcreteMapBTest {
    @Test
    public void testPutCase1 {          
       ...
    }
    @Test
    public void testPutCase2 {          
       ...
    }
    @Test
    public void testGetCase1 {         
       ...
    }
    ...
 }

So what could be the right way to test such? How to reuse these testMethods? Or maybe I just should not do the reuse for unit testing?

Thanks!

Lubor
  • 989
  • 3
  • 10
  • 33
  • https://stackoverflow.com/questions/752521/running-the-same-junit-test-case-multiple-time-with-different-data – Taylor Mar 02 '18 at 19:02
  • @Taylor I don't think that answers this question though, that is to run the same data in one test class, here what I want to do is to reuse the same test case across two separate test classes – Lubor Mar 02 '18 at 19:07
  • to be clearer, to reuse the same test methods – Lubor Mar 02 '18 at 19:09
  • There are examples in there using different objects for the same test. If you want two test classes to have the same test method, just write a base class and inherit. – Taylor Mar 02 '18 at 20:06
  • Thanks Taylor! That makes sense. I will close this question and link to the ones that solved my issue. – Lubor Mar 02 '18 at 20:44

0 Answers0