mardi 3 novembre 2015

Test both constructor and setters

Let's consider a class like this

public class Element {

private String elementId;
private double[] elementFeatures;

public Element() { }

public Element(String elementId, double[] elementFeatures) throws BadElementInitializationException {

    checkElementId(elementId);
    checkElementFeatures(elementFeatures);

    this.elementId = elementId;
    this.elementFeatures = elementFeatures;
}

private void checkElementId(String elementId) throws BadElementInitializationException {

    if(elementId == null)
        throw new BadElementInitializationException("Element id must not be null");
    if(elementId.isEmpty())
        throw new BadElementInitializationException("Element id must not be empty");
}

private void checkElementFeatures(double[] elementFeatures) throws BadElementInitializationException {

    if(elementFeatures == null)
        throw new BadElementInitializationException("Element features must not be null");
    if(elementFeatures.length == 0)
        throw new BadElementInitializationException("Element features length must be greater than 0");
}

public String getElementId() {
    return elementId;
}

public void setElementId(String elementId) throws BadElementInitializationException {
    checkElementId(elementId);

    this.elementId = elementId;
}

public double[] getElementFeatures() { return elementFeatures; }

public void setElementFeatures(double[] elementFeatures) throws BadElementInitializationException {
    checkElementFeatures(elementFeatures);

    this.elementFeatures = elementFeatures;
}
}

Which unit tests would it make sense to have?

  • Should I test setters, constructors, and methods that check parameters? (it seems a bit redundant to do that)
  • Should I test only constructors and setters, without the private method?
  • Something else?

Additional: should I test combinations of bad parameters in constructor? That is, have a test for each combination of parameters in constructor (even though I'm testing setters for each of parameters)?

Aucun commentaire:

Enregistrer un commentaire