How important is bad parameter testing in unit testing?

Let's say I have a method that takes some arguments and saves them as instance variables. If one of them is null, some code will later fail. Would you change the method to exclude if null arguments were specified and add unit tests to check it or not? If I do this, it gets a little complicated, since javascript has a lot of bad values ​​(null, undefined, NaN, etc.), and since it has dynamic typing, I can’t even check if the correct type of the object was passed.

+5
source share
5 answers

I think it really depends on which API you are testing on the module. If it is a component designed and built for internal use only, and you know that use will be subject to certain restrictions, it can be overflowed to unit test for bad parameters. On the other hand, if you are talking about something for external distribution or using in a variety of situations, some of which are difficult to predict, yes, checking for bad parameters is appropriate. It all depends on the use.

+7
source

I think you really have two different questions.

Firstly, it is best practice to check input parameters, and secondly, to check the unit test descriptor for these situations.

, , - /, / . , , , , .

unit test, NULL, , .

+7

JavaScript typeof, , :

'undefined' == typeof noVariable; // true
var noVariable = null;
'undefined' == typeof noVariable; // false
typeof noVariable; // 'object'
noVariable === null; // true

var myArray = [];
typeof myArray; // 'object'
myArray instanceof Object; // true
myArray instanceof Array; // true

var myObject = {};
typeof myObject; // 'object'
myObject instanceof Object; // true
myObject instanceof Array; // false

"" :

function myFunction(foo,bar) {
    foo = foo instanceof Array ? foo : []; // If 'foo' is not an array, make it an empty one
    bar = bar instanceof Number ? bar : 0;

    // This loop should always exit without error, although it may never do a single iteration
    for (var i=0; i<foo.length; i++) {
        console.log(foo[i]);
    }

    // Should never fail
    bar++;
}

:

function myFunction(blat) {
    var blat = blat||null; // If 'blat' is 0, '', undefined, NaN, or null, force it to be null

    // You can be sure that 'blat' will be at least *some* kind of object inside this block
    if (null!==blat) {
    }
}
+1

, , JavaScript . , .

0

- . . .

, , - . , , . .

0

All Articles