简体   繁体   中英

Java JUnit4: Make simple assertEquals Test pass

I am trying to make a simple test using assertEquals pass -- in my case: assertEquals(bob,cell.getLifeForm());.

The first test assertTrue(success); works, meaning boolean success = cell.addLifeForm(bob); works.

But I cannot get assertEquals(bob,cell.getLifeForm()); to pass. I believe I had to add the instance variable LifeForm myLifeForm; so the Cell class can keep track of a LifeForm, and now I need to return the instance variable in getLifeForm() as well as update addLifeForm to modify the instance variable correctly (having trouble with this one). Thank you.

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
   }

}

You have two assertEquals(bob,cell.getLifeForm()); lines.

In the first one, if you are doing this.myLifeForm = entity in addLifeForm method then it will pass. In the second one, if you are doing if (this.myLifeForm == null) this.myLifeForm = entity in addLifeForm method then it will pass.

In your case, I would say the test is working correctly, that is, it's catching an implementation error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM