Java JUnit4: Make simple assertEquals Test pass

335 views Asked by At

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
   }

}
1

There are 1 answers

0
m4ktub On BEST ANSWER

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.