mercredi 27 avril 2016

Testing calculation functions without reimplementing

Lets say I'm writing a function that does a series of related aggregations on a given data.

f(x,y) => { foo: 50, bar: 40, baz: 103 }

How can I write a unit test for this function without re-implementing it?

A trivial example is to have specific pre-determined test cases

it('Should multiply two numbers', () => {
  expect(multiply(2, 5)).to.equal(10);
});

Wouldn't it be better to test it like this?

it('Should multiply two numbers reliably', () => {
  let a, b;
  for (var i = 0; i < 1000; i++) {
    a = ~~(Math.random() * 100);
    b = ~~(Math.random() * 100);
    expect(multply(a, b)).to.equal(a * b);
  }
});

If so, should I do that without re-implementing multiply with a * b? In this case its trivial, but when I'm doing a transformation a more complicated calculation, should I not be doing random/dynamic testing? Or should I just copy the implementation when it works, so that if the implementation is ever optimized or otherwise changed, it checks it against a verified implemntation?

Aucun commentaire:

Enregistrer un commentaire