2015-06-09 3 views
1

Я пытаюсь сделать простой тест, используя passer assertEquals - в моем случае: assertEquals (bob, cell.getLifeForm()) ;.Java JUnit4: Сделать простой assertEquals Test pass

Первый тест assertTrue (успех); works, означающий 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 
    } 

} 
+0

Ваш метод 'addLifeForm' просто возвращает' true', не делая ничего полезного. Как вы ожидаете, что будет хранить ссылку на «LifeForm»? –

+0

addLifeForm (объект LifeForm) фактически не задает переменную экземпляра myLifeForm – Bobby

ответ

2

У вас есть две assertEquals(bob,cell.getLifeForm()); линии.

В первом случае, если вы делаете this.myLifeForm = entity в методе addLifeForm, то он пройдет. Во втором случае, если вы делаете if (this.myLifeForm == null) this.myLifeForm = entity в методе addLifeForm, тогда он пройдет.

В вашем случае я бы сказал, что тест работает правильно, то есть он улавливает ошибку реализации.

+0

Вы правы - спасибо. – user3393266

Смежные вопросы