Java JUnit4:使简单的assertEquals测试通过

时间:2015-06-09 19:01:12

标签: java junit junit4

我正在尝试使用assertEquals传递进行简单测试 - 在我的情况下:assertEquals(bob,cell.getLifeForm());.

第一个测试assertTrue(成功);作品,意思是布尔成功= 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
   }

}

1 个答案:

答案 0 :(得分:2)

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

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

在你的情况下,我会说测试工作正常,也就是说,它正在捕捉实现错误。