How to write tests for classes with inheritance

645 views Asked by At

I have a project written in Angular 1.3 that have services that inherit each other. There is a BaseApiService, which is a parent class and it implements a lot of functionality related to API calls. It looks like that:

.factory('BaseApiService', function ($resource, apiHost, apiUrl, WebSocketService, $q, $timeout) {

  //initializer
  return function (resourceName, options) {
    options = angular.extend({}, {
      resourceUrl: resourceName + '/:id',
      resourceParams: {id: '@id'},
      resourceMethods: {
        'get':    {method:'GET'},
        'update': {method:'PUT'},
        'save':   {method:'POST'},
        'all':    {method:'GET', isArray:true},
        'remove': {method:'DELETE'},
        'delete': {method:'DELETE'}
      }
    }, options);


    this.loadCache = function () {
      //...
    };

    this.new = function () {
      //...
    };

    this.get = function (id) {
      //...
    };

    this.getBy = function (propertyName, value) {
      //...
    };

    this.all = function (params) {
      //...
    };

    //lots of other methods here

Then there are multiple children classes that implement access to the specific API end-points. They are done like that:

.factory('HandymanTasks', function(BaseApiService, $q){

  var service = new BaseApiService('handyman_tasks');

  angular.extend(service, {
    getByRoomId: function(room_id){
      return service.getBy('room_id', room_id);
    },
    capturePhoto: function() {
      //...
    }
  });

  return service;
});

Children services for the most part use parent's methods and only add a few of their own. Parent class is only instantiated for the sake of inheritance, it isn't used on it's own. My question is: how to properly write tests in this scenario? I need to ensure the all the API access functions work in all the children classes. My ideas are:

  • Write a helper that tests all the API access functions (that are implemented in the parent) and then call it in tests for all children classes;
  • Test API calls in the parent class, assume that they work in children classes, since I know that they are always inherited. Test only for their own functions in children classes;
  • Test that children have all the methods of the parents defined, assume that they work properly, because the parent class is covered by tests;

Basically, I just want to ensure that all the functionality of the children classes work properly, but don't have too much copy-pasted/very similar tests in a test suit for each class.

1

There are 1 answers

0
TDDdev On

I think you would be fine with the approach of testing the parent service and then only testing the functions/properties specific to the children services. Your Base service functions only really need to be tested once because each child calls to the same functions so testing each of those would be unnecessary.