gpt4 book ai didi

Java JUnit4 : Make simple assertEquals Test pass

转载 作者:行者123 更新时间:2023-11-30 03:23:47 26 4
gpt4 key购买 nike

我正在尝试使用assertEquals pass 进行一个简单的测试——在我的例子中:assertEquals(bob,cell.getLifeForm());。

第一次测试assertTrue(success);有效,意味着 boolean success = cell.addLifeForm(bob);有效。

但是我无法得到assertEquals(bob,cell.getLifeForm());通过。我相信我必须添加实例变量 LifeForm myLifeForm;因此 Cell 类可以跟踪 LifeForm,现在我需要在 getLifeForm() 中返回实例变量,并更新 addLifeForm 以正确修改实例变量(在这个方面遇到问题)。谢谢。

TestCell.java:

import static org.junit.Assert.*;
import org.junit.Test;
/**
* The test cases for the Cell class
*
*/
public class TestCell
{
/**
* Checks to see if we change the LifeForm held by the Cell that
* getLifeForm properly responds to this change.
*/
@Test
public void testSetLifeForm()
{
LifeForm bob = new LifeForm("Bob", 40);
LifeForm fred = new LifeForm("Fred", 40);
Cell cell = new Cell();
// The cell is empty so this should work.
boolean success = cell.addLifeForm(bob);
assertTrue(success);
assertEquals(bob,cell.getLifeForm());
// The cell is not empty so this should fail.
success = cell.addLifeForm(fred);
assertFalse(success);
assertEquals(bob,cell.getLifeForm());
}
}

Cell.java:

/**
* A Cell that can hold a LifeForm.
*
*/
public class Cell
{
LifeForm myLifeForm;
//unsure about the instance variable

/**
* Tries to add the LifeForm to the Cell. Will not add if a
* LifeForm is already present.
* @return true if the LifeForm was added the Cell, false otherwise.
*/
public boolean addLifeForm(LifeForm entity)
{
return true;
//modify instance variable
}


/**
* @return the LifeForm in this Cell.
*/
public LifeForm getLifeForm()
{
return myLifeForm;
//return instance variable
}

}

最佳答案

您有两行 assertEquals(bob,cell.getLifeForm()); 行。

在第一个中,如果您在 addLifeForm 方法中执行 this.myLifeForm =entity ,那么它将通过。在第二个中,如果您在 addLifeForm 方法中执行 if (this.myLifeForm == null) this.myLifeForm =entity ,那么它将通过。

就您而言,我会说测试工作正常,也就是说,它捕获了实现错误。

关于Java JUnit4 : Make simple assertEquals Test pass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30740612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com