samedi 14 février 2015

Mockitio - returning null when expecting mock in unit test

I have a method in a class called FruitBasket which I would like to test as so:



// Method to test
public Fruit getFruit(String fruitName) {
Fruit fruit = new Fruit();

if(fruitExists(fruitName)) {
fruit = getFruitByName(fruitName);
}
else {
fruit.setFruitName(fruitName);
saveFruit(fruit);
fruit = getFruitByName(fruitName);
}

return fruit;
}



private Fruit getFruitByName(String fruitName) {
return fruitDao.getFruitByName(fruitName);
}

public boolean fruitExists(String fruitName) {
return fruitDao.fruitExists(fruitName);
}


I have written a unit test for this method as follows:



@Mock
FruitDao fruitDao;
@Mock
Fruit mockFruit;

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}

@Test
public void testgetFruitMethod() {
FruitBasket fruitBasket = new FruitBasket (fruitDao);
Fruit apple = fruitBasket.getFruit("Apple");

when(fruitDao.fruitExists(anyString())).thenReturn(true);
when(fruitDao.getFruitByName(anyString())).thenReturn(mockFruit);

assertThat(apple, instanceOf(Fruit.class));
}


However the test fails with an assertion error. An instance of Fruit was expected but null was returned instead.


Can anyone spot an issue to why I am getting null?


Aucun commentaire:

Enregistrer un commentaire