【问题标题】:testcase not working properly. Issue setting two numbers equal to each other测试用例无法正常工作。问题设置两个数字彼此相等
【发布时间】:2017-04-05 05:06:38
【问题描述】:

我正在处理一个测试用例,但遇到了麻烦。我很难让我的测试用例正常工作。代码如下:

    public class Appointment extends Actor
    {
        int hour;
        String description;

        public Appointment(int hour, String description)
        {
            super();
            this.hour = hour;
            this.description = description;
        }


        public void setHour(int newHour)
        {
            newHour = hour;
        }
    }

/////////

public class AppointmentTest extends TestCase
{

    private Appointment appointment;
    private int hour;
    private String description;
    private String newDescription;
    private int newHour;

    public AppointmentTest()
    {

    }


    public void setUp()
    {
        appointment = new Appointment(hour, description);
        this.hour = hour;
        this.description = description;
        hour = 7;
        description = "";
        newHour = 1;
        newDescription = "hello";
    }

    public void testSetHour()
    {
        appointment.setHour(1);
        assertEquals(newHour, hour);
    }
}

问题是当我运行我的测试用例时,它说 newhour is 7 ad hour 仍然是 1。有谁知道为什么?

【问题讨论】:

  • hournewHour 都没有更改代码...您确定已发布所有相关代码吗? (请参阅minimal reproducible example 以获得指导)
  • 我的意思是我可以发布我所有的代码。但这就是我认为与问题相关的所有代码。如果我只发布所有内容会有所帮助吗?
  • 如果是这种情况,您可能想阅读一些有关 Java 的内容...看起来您假设值是通过引用传递的 - 请查看 stackoverflow.com/questions/3326112/…

标签: java testcase


【解决方案1】:

您发布的代码中有多个错误 -

1.

public void setHour(int newHour)
{
    newHour = hour;
}

在 Appointment 类中没有名为 newHour 的实例变量。 即使它是从 Actor 类继承的,您也没有使用 this.newHour 来设置它,因此您的逻辑在这里似乎有问题。

2.

public void setUp()
{
    appointment = new Appointment(hour, description);
    this.hour = hour;
    this.description = description;
    hour = 7; //this statement is overriding your this.hour = hour statement. what is the point?
    description = ""; //this statement is overriding your this.description = description statement. what is the point?
    newHour = 1;
    newDescription = "hello";
}

3.

public void testSetHour()
{
    appointment.setHour(1); // this statement doesn't make any difference for next assertEquals statement. It changes instance variable hour, not the local variable.
    assertEquals(newHour, hour);
}

在调用 assertEquals 时,newHour 是 1,hour 是 7。 所以,

问题是当我运行我的测试用例时,它说 newhour 是 7 ad hour 仍然是 1

不成立。

【讨论】:

  • 很高兴它有效。你总是可以接受答案并投票:P
猜你喜欢
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多