测试构造函数和setter

时间:2015-11-03 09:21:42

标签: unit-testing testing junit

让我们考虑一下这样的课程

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;
}
}

哪些单元测试有意义?

  • 我应该测试检查参数的setter,构造函数和方法吗? (这似乎有点多余)
  • 我应该只测试构造函数和setter,而不使用私有方法吗?
  • 别的什么?

补充:我应该在构造函数中测试错误参数的组合吗?也就是说,对构造函数中的每个参数组合进行测试(即使我正在测试每个参数的setter)?

1 个答案:

答案 0 :(得分:0)

你应该测试让你害怕的一切。你害怕吸气吗?你觉得它可能会破裂吗?我不会测试它。有一个与setter不同的故事 - 它们包含逻辑

关于私有方法:测试它们通常会使您的代码更难以更改。例外情况是在许多地方使用私有方法。然后进行测试可能会为您节省大量时间和代码。

但是在您的情况下,问题不是私有方法,而是代码重复。构造函数和setter共享相同的代码。重构因此你的构造函数使用setter然后你需要的只是测试构造函数 - setter将免费测试。

相关问题