Search code examples
javaspring-bootclasstestingjunit

How to make a base test class for testing common methods (like CRUD) of different repositories?


If I have 2 repositories, say employees and departments, and they both have the common CRUD operations. Is there a way by which I can make a common base class for testing the common methods in them?

In my actual code, I have

public interface EntityRepo<E, ID> {
    E findById();
}

Its implementing class:

public class EntityRepoImpl<E, ID> implements EntityRepo<E, ID>{
   // method implementing findById()
}

My other 2 repository interfaces look like this:

public interface EmployeeRepo extends EntityRepo<Employee, Long>{

}
public interface DepartmentRepo extends EntityRepo<Department, Long>{

}

I want to test the findById using Junit for both repos using a base test class. How will I do it?


Solution

  • I agree on comments about "This isn't a purpose of unit test" etc. But if you still need to do that, maybe, you can do it like this

    public abstract class BaseRepoTest <T extends EntityRepo> {
    
        @Autowired
        T repo;
    
        @Test
        public void testRepo() {
            repo.findById(1L);
        }
    }
    

    Then you can create your sub classes like following:

    public class EmployeeRepoTest extends BaseRepoTest<EmployeeRepo> {
    }
    

    and

    public class DepartmentRepoTest extends BaseRepoTest<DepartmentRepo> {
    }
    

    Since they extends abstract base test class, tests should be run for 2 subclasses with provided Repo classes.