简体   繁体   中英

How should I unit test code with a lot of overlap?

I'm relatively new to unit testing. I'm writing a small JavaScript library where I've prioritized a friendly API, which leads to some method overlap for the sake of convenient usage.

As a simple, hypothetical example, consider the following:

var BasicMath = function() {};

BasicMath.prototype.multiply = function(numA, numB) {
  return numA * numB;
};

BasicMath.prototype.square = function(num) {
  return this.multiply(num, num);
};

How should I unit test this code?

Note that .square() is just a convenience method that does nothing but pass along its argument twice to .multiply() .

With that in mind, should I:

  • write similar (or even identical) unit tests for both methods?
  • test that .square() calls .multiply() with certain arguments? (My understanding is that this is bad practice, since it relies too heavily on the method's implementation details.)
  • not test .square() at all, since it's essentially redundant to .multiply() ?
  • test only the more general aspects of .square() (like argument type, quantity, etc.), to avoid redundancy with .multiply() ?

Or, some other approach?

Please keep in mind that the code above is just a contrived example - I'm asking a more general question about how to unit test methods with overlapping/redundant functionality.

Example using jasmine and sinon:

test Multiply like any other method:

it('multiplies two numbers', function () {
    math = new BasicMath();
    expect(math.multiply(2,3)).toBe(6);
}

with square , you want to test that it calls multiply passing as both arguments the value of num and returns the result returned by multiply without performing any other logic:

it('squares a number', function () {
    math = new BasicMath();
    math.multiply = sinon.stub();
    math.multiply.withArgs(2,2).returns(4);

    expect(math.square(2)).toBe(4);
}

what you do with this is create a reproducible environment using a stub, which will always expect the call to be with two identical args (in this case 2 and 2), which tests that square is sending num and num (and not num and num + 1 for example), and returns the result of the call to multiply (you could tell the stub to return 'banana' and check for 'banana' , what's important is square returns whatever multiply returns)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM