jeudi 31 mars 2016

Which approach is best to unit test composed code?

Say I have the following AngularJs service:

angular.module("foo")
    .service("fooService", function(){
        var svc = this;

        svc.get = function(id){...};
        svc.build = function(id){...};
        svc.save = function(thing){...}; //posts, then returns the saved thing
        svc.getOrCreate = function(id){
            return svc.get(id).then(function(thing){
                return thing || svc.build(id).then(function(builtThing){
                    return svc.save(builtThing);
                });
            });
        }
    });

I can unit test the get method by making sure the right API endpoint is being reached, with the right data.

I can test the build method by making sure it pulls data from the proper endpoints/services and builds what it's supposed to.

I can test the save method by making sure the right API endpoint is being reached.

What should I do to test the getOrCreate method? I get two differing opinions on this:

  1. stub the get, build and save methods and verify they're called when appropriate, and with the proper parameters
  2. stub the API endpoints that are being called in get and build, then verify that the endpoints within save are being called with the proper parameters

The first approach is basically saying, "I know these three methods work because they're independently tested. I don't care how they actually work, but I care that they're being called within this method."

The second approach is saying, "I don't care about how this method acts internally, just that the proper API endpoints are being reached"

Which of these approaches is more "correct"? I feel the first approach is less fragile since it's independent of how the get, build and save methods are implemented, but it's not quite right in that it's testing the implementation instead of the behavior. However, option 2 is requiring me to verify the behavior of these other methods in multiple test areas, which seems more fragile, and fragile tests make people hate programming.

This is a common tradeoff I find myself facing quite often with tests... anybody have suggestions on how to handle it?

Aucun commentaire:

Enregistrer un commentaire