Java JUnit4 : Make simple assertEquals Test pass

标签 java junit junit4

我正在尝试使用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/

相关文章:

junit - 如何使用 EasyMock(不使用 Joda Time 和 PowerMock)将当前系统时间覆盖到 Java 8 Web 应用程序中的特定日期?

java - Avro 架构和生成的文件中的十进制数据类型支持

用于泛型的 Java JSON 库

java - 编写与Java变量声明相关的自定义规则

java - 如何在正在运行的线程中持久保存请求对象?

java - JUnit Spring 4 MVC 集成测试失败并出现 BeanCreationException : Error creating bean

java - 您如何断言在 JUnit 测试中引发了某个异常?

java - 自定义调用 TestSuite 的多个 TestExecutionListeners 方法的最佳方法是什么?

java - 在编写实际代码之前在测试驱动开发中编写 junits?

java - 将所有测试项目设置为SpringBoot和junit并行工作后并发修改异常