【问题标题】:JUnit Test Method for a method that returns a string用于返回字符串的方法的 JUnit 测试方法
【发布时间】:2015-10-30 03:10:31
【问题描述】:

下面是我的 Cylinder 类,然后是我试图用来测试我编写的 getLabel 方法的 JUnit 测试。在测试用户将输入的字符串时,我无法理解如何正确形成测试方法。

public class Cylinder {
   private String label = "";
   private double radius;
   private double height;
   private static int count = 0;

   /**
   * Creates a new Cylinder object with a given label, radius, and height.
   * 
   * @param label2 The name of the cylinder returned as a String.
   * @param radius2 The radius of the cylinder as a double.
   * @param height2 The height of the cylinder as a double.
   */
   public Cylinder(String label2, double radius2, double height2, int count2) {
      setLabel(label2);
      setRadius(radius2);
      setHeight(height2);
      setCount(count2);
   }
   /**
   * This method is respondible for getting the label from the user 
   * and returns a string representation of the label.
   *
   * @return String representation of the label of the Cylinder.
   */
   public String getLabel() {
      return label;
   }

下面是我的 JUnit 测试类,我用它来为我的 Cylinder 类中的每个方法创建一个测试。

public class CylinderTest {

   private String label = "";
   private double radius;
   private double height;

   /*
   *
   */
   @Test public void labelTest() {
      Cylinder c1 = new Cylinder("", radius, height);

      String result = c1.getLabel(label);

      Assert.assertEquals(" ", label);

【问题讨论】:

  • 那么你想要做的是设置标签然后断言标签是什么?正确的??如果是这样,它看起来很接近我,您在测试中调用构造函数,该构造函数将标签作为空字符串传入,构造函数设置标签。您的代码获取 Cylinder 类,使用 getLabel(label) [我相信只需 getLabel() 而不是 getLabel(label)] 调用 getLabel,然后断言它是什么。在断言中,尽管您有一个开始时没有的空​​间。您应该断言它是一个空字符串。例如。 ""

标签: java unit-testing testing methods junit


【解决方案1】:

在上面的代码中,您正在有效地测试不是commonly accepted practice. 的getter 和setter

当您将标签传递给构造函数时,您希望它是圆柱体的标签。没有发生转变。您只是在测试一个变量是否可以设置为一个不太可能中断的值。我们希望将测试集中在行为上。

但是,在上面的 labelTest 中,您将一个空字符串传递给构造函数,但在 assertEquals 中需要一个空格字符。如果这是所需的行为,则确实需要进行测试。您还应该为测试命名以说明其行为方式的原因(test_GetLabel_ExpandsEmptyStringToSpace 或类似名称)。

在您的代码中,我将更多地关注参数如何交互。例如,给定一个半径和一个高度,您可以编写一个体积测试来显示这两个参数如何相互关联。比如

@Test public void test_VolumeCalculation() {
  Cylinder c1 = new Cylinder("", 2.0, 4.5);

  String actual = c1.getVolume();

  Assert.assertEquals(56.55, actual, 0.001);
}

我遇到了一些参数混乱的代码,因此您可以考虑编写测试来显示将半径和高度值分配给正确的字段。由于它们都是双精度值,因此可能会以错误的顺序传递值,但测试只能证明您正确分配了值,并且不会阻止调用者将它们混淆。

您的代码在构造函数中也有四个参数,但在测试的构造函数调用中只出现了三个。您可能需要清理您的问题以查明您要问的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多